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 trial

Python Python Collections (2016, retired 2019) Dictionaries Dictionary Basics

Trying to insert a list and dictionary inside another dictionary.

Hello guys,

At first I tried to create my dictionary like this:

dictionary = {["levels", [1,2,3,4]], "items": {"key1": 3, "key2": "value2"}}

it didn't work and a friend told me to try to insert the list and the dictionary like this, can somebody show me how you solve it please?

dicts.py
player = {"name": "string", "remaining_lives": 3}

numbers_list = [1, 2, 3, 4]
dictionary["levels"] = numbers_list

items_dict = {"key1": 3, "key2": "value2"}
dictionary["items"] = items_dict

dictionary = { }

2 Answers

Sure Krishna, I do that by clicking "unfollow discussion right"?

List is collection of elements(which can be of different types). Dictionary is Key-Value pair and a list cannot be a key(tuples can be though)(Google it, and you'll find why).

for what you have tried:

dictionary = {["levels", [1,2,3,4]], "items": {"key1": 3, "key2": "value2"}}

in above code, dictionary dont have a key-value pair for first item. i could have been something like:

dictionary = { "levels": [1,2,3,4], "items": {"key1": 3, "key2": "value2"}}

As for solution, lets go line by line, see the comments for more details.

#make a dictionary named player.
player = {}

#Add two keys to it.
#first key should be "name" and the value can be any string you want.
player["name"]="Any string i want"

#second key should be "remaining_lives". Set this key's value to 3.
player["remaining_lives"] = 3

#add a "levels" key. It should be a list with the values 1, 2, 3, and 4
player["levels"] = [1, 2, 3, 4]

#add an "items" key. This key's value should be another dictionary.
player["items"] = {"one  key": "one value"}

Hi Krishna thank you! :) my mistake was actually I though I needed to have a different dictionary for "levels" and "items" Now it worked! ;)

Sorry about that, Tiago. I think they dont have option to close the question, rather accept the answer or just upvoting should be sufficient.

Have fun coding.