Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Error , iterating list of dictionaries

I get error iterating list of dictionaries
custom_list – list of dictionaries
each dictionary have 3 keys

for i in custom_list:
    for link, id, timestamp in i.items():
        print("id : ", id)
        print("link : ", link)
        print("timestamp : ",timestamp)

The error:

    for link, id, timestamp in i.items():
ValueError: not enough values to unpack (expected 3, got 2)

if i print ‘ i ‘ i can see i have 3 values
example of ‘ i ‘ dictionary print

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'id': 1, 'link': 'https://www.link.com/', 'timestamp': '2022-03-25 01:11:11.11111111'}

>Solution :

i in the first for loop will give a dictionary so you can directly reference the key value pair without another for loop

for i in custom_list:
    print("id : ", i['id'])
    print("link : ", i['link'])
    print("timestamp : ",i['timestamp'])

If the dictionary’s structure is dynamic and you want to iterate for all the key value pairs in the dictionary of current iteration you can add the following

for i in custom_list:
    for key, val in i.items():
        print(f'{key}: {value}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading