-2

I have written code to create a set of dictionaries. Where I am expecting the output elements to be printed in a meaningful format, however, I am getting an error.

sets_of_dictionary_ele  = {{"name": "Rolf", "grade": "First"},
                           {"name": "Mark", "grade": "Second"},
                           {"name": "John", "grade": "Third"},
                           {"name": "Halen", "grade": "Fourth"}
                           } 

for k,v in sets_of_dictionary_ele:

    name = k["name"]
    grade = v["grade"]

    print(f"{name} has scored {grade} grade.")
CDJB
  • 14,043
  • 5
  • 29
  • 55
  • It would help to know what error you are getting - at a guess it's because you can't store multable objects like a dictionary in a set? – DavidW Jan 03 '20 at 13:34
  • Does this answer your question? [TypeError: unhashable type: 'dict'](https://stackoverflow.com/questions/13264511/typeerror-unhashable-type-dict) – DavidW Jan 03 '20 at 13:41

1 Answers1

2

The reason you get this error is because you are wrapping the dicts with curly brackets, which attempts to make a set. Dictionaries are unhashable, so they can't be members of sets. You can either use square brackets to make a list of dicts, and alter your for loop accordingly, as follows:

sets_of_dictionary_ele  = [{"name": "Rolf", "grade": "First"},
                           {"name": "Mark", "grade": "Second"},
                           {"name": "John", "grade": "Third"},
                           {"name": "Halen", "grade": "Fourth"}
                           ]

for k in sets_of_dictionary_ele:
    name = k["name"]
    grade = k["grade"]

    print(f"{name} has scored {grade} grade.")

Or, you can alter the format of your sets_of_dictionary_ele variable to a dictionary and do the following:

sets_of_dictionary_ele = {'Rolf': 'First',
                          'Mark': 'Second',
                          'John': 'Third',
                          'Halen': 'Fourth'}

for k, v in sets_of_dictionary_ele.items():
    name = k
    grade = v
    print(f"{name} has scored {grade} grade.")
CDJB
  • 14,043
  • 5
  • 29
  • 55