Python Forum
Line of code to show dictionary doesn't work - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Line of code to show dictionary doesn't work (/thread-28646.html)



Line of code to show dictionary doesn't work - MaartenRo - Jul-28-2020

Hi,

I am trying to write a line of code that should return the names and their favourite colors. Somehow it won't work. What am i doing wrong? I don't get an error messgae just nothing happens when i press enter after the code.

Thanks in advance!

>>> Colors = {"Sam": "Blauw", "Ali": "Rood", "Saar": "Geel"}
>>> Colors
{'Sam': 'Blauw', 'Ali': 'Rood', 'Saar': 'Geel'}
>>> Colors.keys()
dict_keys(['Sam', 'Ali', 'Saar'])
>>> for Item in Colors.keys():
	print("{0} houdt van de kleur {1}."
	      .format(Item, Colors{Item}))
	
SyntaxError: invalid syntax
>>> for Item in Colors.keys():
	print("{0} houdt van de kleur {1}."
	      .format(Item, Colors[Item]))



RE: Line of code to show dictionary doesn't work - ndc85430 - Jul-28-2020

Did you forget to indent the print inside the for? Also, a few things:

1. Dictionaries are iterable and iterating over them gives you the keys, so calling keys explicitly is unnecessary.

2. If you want both the key and the value, you can use items:

>>> d = {"foo": 1, "bar": 2}
>>> for key, value in d.items():
...     print(key, value)
... 
foo 1
bar 2



RE: Line of code to show dictionary doesn't work - deanhystad - Jul-28-2020

Use Colors['Sam'] to get Sam's favorite color. You can also use Colors.get('Sam'). get is useful when looking up keys that may not be in the dictionary. Colors['Bob'] will throw an exception, but Colors.get('Bob', 'Green') will return 'Green', a default value used when the key is not found.

This code can use [] because the keys are guaranteed to be in the dictionary.
Colors = {'Sam': 'Blauw', 'Ali': 'Rood', 'Saar': 'Geel'}

for Item in Colors:
    # print("{0} houdt van de kleur {1}.".format(Item, Colors[Item])) # Works
    print(f'{Item} houdt van de kleur {Colors[Item]}.')) # Works, shorter, reads better