Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTiago Ramos
2,380 PointsTrying to insert a list inside the dictionary
Hi friends,
I'm trying to insert this list inside the dictionary, this is the 3rd time I try. Please somebody show me how I do it, I worked hard on this.
By the way, to insert the dictionary inside a dictionary I just need to declare it like a did rigth?
Thans a bunch mates :)
player = {"name": "string", "remaining_lives": 3}
dictionary = {"items":{"key1": 3, "key2": "value2"}}
levels = {"levels": [1, 2, 3, 4]}
dictionary.update(levels)
1 Answer
Jon Mirow
9,864 PointsHi there!
The update method of a dictionary is for importing the key:value pairs of another dictionary. Is this what you were looking to achieve?
Your question sounds like you wanted to know how to add lists or dictionaries to existing dictionaries? Just to recap, only imutable types can be keys (no lists, dictionaries, sets, user defined objects without a "hash" method), but anything can be a value. For example
my_dict = {}
# Add a list:
my_dict["my_list"] = [3, 1, 4, 1, 5, 9, 2]
# Add a dictionary:
my_dict["sub_dict"] = {"key": "value"}
# Add a set:
my_dict["my_set"] = set([3, 1, 4, 1, 5, 9, 2])
# Add a Tuple as a key and as a value:
my_dict[(27.9878, 86.9250)] = ("Everest", "Nepal", 8848)
# Prove it all worked:
for key, value in my_dict.items():
print("Key: {}\nValue: {}\n\n".format(key,value))
Note if a tuple is a key, all the values in the tuple must be valid key types too :)
Hope it's helpful
Krishna Pratap Chouhan
15,203 PointsKrishna Pratap Chouhan
15,203 Pointshttps://teamtreehouse.com/community/trying-to-insert-a-list-and-dictionary-inside-another-dictionary