Ask coding questions

← Back to all posts
Dictionary help
mkhoi (215)

Lets say that i've convert a dictionary into a list, now i want to convert it back to a dictionary and it still have the original values of the keys


import random

dict = {
    "one": 1,
    "two": 2,

num = random.choice(list(dict))

print(dict.values()) # error that a list doesn't have a value
Answered by Geocube101 (528) [earned 5 cycles]
View Answer
Geocube101 (528)

I don't know how this would actually be done with python keywords (I'd just created a nested array containing the key value pairs)

def dict_to_list(dictionary):
	out = []
	for k, v in dictionary.items():
		out.append([k, v])
	return out

def list_to_dict(array):
	out = {}
	for a in array:
		out[a[0]] = a[1]
	return out
mkhoi (215)

@Geocube101 Sorry for replying late, i was busy but anyways this worked, thank you!