简体   繁体   中英

i've a list of values and I would like to iteratively append key-value pair to a python dictionary

i've a list of values and I would like to iteratively append key-value pair to a python dictionary

lst = ['12233223','23232423','23453443']

i'm looking output like this:

new_list = [{'id':'12233223', 'new_id':'d2233223'},{'id':'13232423','new_id':'d3232423'}]

but I'm getting this

[{'id':13453443,'new_id':13453443},{'id':13453443,'new_id':13453443}]

Here is my code

lst = [{'id':'12233223'},{'id':'13232423',} {'id':'23453443'}]
d={}
new_list=[]
for each in lst:
    d['id']= each
    if len(each)==8 and each[0]==1:
    new_id = each.replace('1','d',1)
    d['new_id'] = new_id
    new_list.append(d)

same value is added to the list for two times

You can't have a dict with all keys bearing the same value. But you can have a list of dicts instead

new_list = [{'id': each} for each in lst]

You can use a list comprehension to go through your list of dictionaries with a nested for to get to the values. Then apply the filter condition and build new dictionaries from the eligible dictionaries/values:

lst = [{'id':'12233223'},{'id':'13232423'}, {'id':'23453443'}]


new_list = [ {**each,'new_id':"d"+n[1:]} for each in lst 
             for n in each.values() if len(n)==8 and n[0]=='1' ]

print(new_list)
              
[{'id': '12233223', 'new_id': 'd2233223'}, 
 {'id': '13232423', 'new_id': 'd3232423'}]

If the dictionaries in lst have other keys, you can make the nested for more specific to obtain just the value of the 'id' keys:

new_list = [ {**each,'new_id':"d"+n[1:]} for each in lst 
             for n in [each['id']] if len(n)==8 and n[0]=='1' ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM