Why is there an issue when I add pocket to the dictionary?


Why is there an issue when I add pocket to the dictionary?


There are two ways we’ve seen to add a key-value pair to an existing dictionary:

  1. Adding it into the existing dictionary by typing out the key and value pair, like so:
inventory = {
  'gold' : 500,
  'pouch' : ['flint', 'twine', 'gemstone'], 
  'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'],
  'new_key_name' : "New value!"
  1. Or accessing the dictionary with a new key and assigning a value to it, like this:
inventory['new_key_name'] = "New value!"

The most common mistake with the first method is missing the comma at the end of the last item in the existing dictionary. Be sure to always have a comma after a dictionary value if you’ve got another key after it!


You can also have the code since the instruction says add not change the value:

inventory['gold] = inventory[‘gold’] + 50


Hi. There is also another, more laconic option:


thanks man, really helped me out.

1 Like

Thanks indeed, I had to read the instructions again. I kept on changing the value to 50 when it fact it should have been 550. I like your solution too.

1 Like

Another question. The way to browse the lists (loop for or while) is it the same for a dictionary ?

1 Like

We access dictionaries through their keys. If we don’t care the order, then just use the in operator in a for loop. Previous to Python 3.6 dictionaries did not remember the order of insertion and iteration order was somewhat random. Post Python 3.6 dictionaries do retain insertion order (not to be confused with alphabetical).

for key in object:
    print ("{key}: {value}".format(key=key, value=object[key])

If we want the keys alphabetical,

for key in sorted(object):
    print ("{key}: {value}".format(key=key, value=object[key])


for key in sorted(object.keys()):
    print ("{key}: {value}".format(key=key, value=object[key])

Now let’s see if it works. First we’ll create some raw data.

>>> raw_data = "a quick brown fox jumps over the lazy dog".split()
>>> raw_data += "the rain in Spain falls mainly in the plains".split()
>>> raw_data += "a bird in the hand is worth two in the bush".split()
>>> raw_data += "many a comet falls into the sun".split()

Every word in the strings above is a list element. Their order is preserved but we don’t really care about that. Good to know, though.

We wish to make this into a dictionary of words and their word count, known as a histogram. To set this up we’ll buzz through the list and create a dictionary of keys, giving them a value of zero.

>>> raw_dict = {k: 0 for k in raw_data}

Now we can buzz through the list once more and add to the count of each word (key) in the dictionary.

>>> for k in raw_data:
	raw_dict[k] += 1

We now have a dictionary full of keys (the words in the list) and a count of their occurrences. Fun time ahead as we sort through this to construct a histogram.

>>> histo = sorted(((v, k) for k, v in raw_dict.items()), reverse=True)

And now we get to express our dictionary in order of keyword occurrence…

>>> for x in histo:
	v, k = x
	print ("{key}: {value}".format(key=k, value=v))

the: 6
in: 4
a: 3
falls: 2
worth: 1
two: 1
sun: 1
rain: 1
quick: 1
plains: 1
over: 1
many: 1
mainly: 1
lazy: 1
jumps: 1
is: 1
into: 1
hand: 1
fox: 1
dog: 1
comet: 1
bush: 1
brown: 1
bird: 1
Spain: 1

Is it possible to return the key-value of dictionary by descending order ? since sorted(object) returns the key-value of dictionary by ascending order


sorted(object, reverse=True)


Thanks!!! it helped me.

1 Like

if a dictionary can contain a list, is it possible that a dictionary contains another dictionary ? it’s for an exercise.


A dictionary may contain any data type that a list can.

key: { key: value }  # dict
key: []              # list
key: ()              # tuple
key: {}              # set
key: str
key: int
key: float
key: bool
key: None

I would like to automatically create a dictionary at each loop turn for. How to do that ?

1 Like

Sorry, I missed this question. Did you solve this problem? If not, please provide us an example from which to work.

1 Like

Yes, It already resolved.
This was my main problem, what I asked you was just a part of my problem


[quote=“wiki-bot, post:1, topic:339165”]
inventory = { ‘gold’ : 500, ‘pouch’ : [‘flint’, ‘twine’, ‘gemstone’], ‘backpack’ : [‘xylophone’,‘dagger’, ‘bedroll’,‘bread loaf’], ‘new_key_name’ : “New value!”


how the order is determined?
Cause in inventory the order is: gold, pouch, pocket and backpack .
But its printed as: pocket, backpack, pouch and gold
This is not alphabetical, and I can understand what is happening.

inventory = {
‘gold’ : 500,
‘pouch’ : [‘flint’, ‘twine’, ‘gemstone’],
‘pocket’ :[‘seashell’,‘strange berry’, ‘lint’],
‘backpack’ : [‘xylophone’,‘dagger’, ‘bedroll’,‘bread loaf’]
print inventory

We will assume this is a Python 2 exercise. In that version, and any previous to Python 3.6, dictionary insertion order is not remembered. The dictionary will not have any order with relation to the order of insertion.

If you wish to have a fixed order when you print, then create a print_inventory function, or a method in the object closure.

def print_inventory(d):
    for x in sorted(d.keys()):
        print (f"{x}: {d[x]}")

1 Like

Thank you!
It’s a Python 2 exercise, and you really helped!
I was going crazy trying to find the logic behind!

1 Like