Python Forum
Line of code to show dictionary doesn't work
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Line of code to show dictionary doesn't work
#3
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
Reply


Messages In This Thread
RE: Line of code to show dictionary doesn't work - by deanhystad - Jul-28-2020, 03:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable to understand the meaning of the line of code. jahuja73 0 328 Jan-23-2024, 05:09 AM
Last Post: jahuja73
  hi need help to make this code work correctly atulkul1985 5 829 Nov-20-2023, 04:38 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 717 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 978 Jun-24-2023, 02:14 PM
Last Post: deanhystad
  Code works but doesn't give the right results colin_dent 2 739 Jun-22-2023, 06:04 PM
Last Post: jefsummers
  PDF properties doesn't show created or modified date Pedroski55 4 1,120 Jun-19-2023, 08:09 AM
Last Post: Pedroski55
  Beginner: Code not work when longer list raiviscoding 2 848 May-19-2023, 11:19 AM
Last Post: deanhystad
  Why doesn't this code work? What is wrong with path? Melcu54 7 1,869 Jan-29-2023, 06:24 PM
Last Post: Melcu54
  Code used to work 100%, now sometimes works! muzicman0 5 1,481 Jan-13-2023, 05:09 PM
Last Post: muzicman0
  color code doesn't work harryvl 1 919 Dec-29-2022, 08:59 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020