Print dictionary of list values

18,514

dict.items returns a tuple of the key value pairs.

Return a new view of the dictionary’s items ((key, value) pairs)

You will have to do this instead.

for key,values in queue_dict.items():
     for v in values:
          print(key," : ",v)

Also you can not concatenate an str object and a dict object using +. You will get a TypeError. So you will have to cast it to a str. Instead you can use format as in print("{} : {}".format(key,v))

Share:
18,514
Auric Goldfinger
Author by

Auric Goldfinger

Updated on June 04, 2022

Comments

  • Auric Goldfinger
    Auric Goldfinger almost 2 years

    I have a list of dictionary values, as given below:

    {'ID 2': [{'game': 586, 'start': 1436882375, 'process': 13140}, {'game': 585, 'start': 1436882375, 'process': 13116}], 'ID 1': [{'game': 582, 'start': 1436882375, 'process': 13094}, {'game': 583, 'start': 1436882375, 'process': 12934}, {'game': 584, 'start': 1436882375, 'process': 12805}]}
    

    It is barely readable. I want to format it this way:

    'ID 2' : {'game': 586, 'start': 1436882375, 'process': 13140},
    'ID 2' : {'game': 585, 'start': 1436882375, 'process': 13116},
    'ID 1' : {'game': 582, 'start': 1436882375, 'process': 13094},
    'ID 1' : {'game': 582, 'start': 1436882375, 'process': 13094},
    

    My code for printing is given below:

     for key in queue_dict.items():
            for values in key.values():
                print(key+" : "+values)
    

    The error is:

    AttributeError: 'tuple' object has no attribute 'values'
    

    I cannot understand how to access each dictionary in the list value of each key. I searched a lot, but couldn't really find an answer. Can someone help?