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

some basic looping through the list of dictionaries and adding the chosen key values to the new dictionary

Got some basic problems with looping through the list of dictionaries. I want to loop through the list called jslist and get an output as I show at the bottom. Basically I want to extract chosen key: value pairs (the ones I paste as an example below – site_id, sitekey, nickname) from the list and store them in another list of dicts.

jslist = [
    {'site_id': '1111111', 'hostname': 'abc.com', 'nickname': 'abc.com', 'sitekey': '29346385345', 'sitekey_admin': '293857349857934857345', 'timezone': '1', 'visitors_online': '1', 'visitors_today': '34'}, 
    {'site_id': '100992048', 'hostname': 'gcd.com', 'nickname': 'gcd.com', 'sitekey': '938573945739453', 'sitekey_admin': '20395734985793', 'timezone': '1', 'visitors_online': '0', 'visitors_today': '2'}]

dict_1 = {}

for k in jslist:
    dict_1['site_id'] = k['site_id']
    dict_1['sitekey'] = k['sitekey']
    dict_1['nickname'] = k['nickname']


print(list(dict_1))

current output:

{'site_id': '100992048', 'sitekey': '938573945739453', 'nickname': 'gcd.com'}

expected output

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

[{'site_id': '100992048', 'sitekey': '938573945739453', 'nickname': 'gcd.com'},{'site_id': '1111111', 'sitekey': '29346385345', 'nickname': 'abc.com'}]

>Solution :

You’re using one dict for each, so you keep appending the same instance, the dict creation should be inside the loop. Also you can store the needed keys in a list to made the code easier to update and proper

Combining with a list comprehension

keep = {'site_id', 'sitekey', 'nickname'}
jslist_new = [{k: item[k] for k in keep} for item in jslist]
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