[英]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我有一个值列表,我想将 append 键值对迭代到 python 字典
lst = ['12233223','23232423','23453443'] lst = ['12233223','23232423','23453443']
i'm looking output like this:我正在寻找 output 像这样:
new_list = [{'id':'12233223', 'new_id':'d2233223'},{'id':'13232423','new_id':'d3232423'}] 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}] [{'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.您可以通过嵌套
for
的字典列表使用对 go 的列表理解来获取值。 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:如果
lst
中的字典有其他键,则可以使嵌套for
具体以仅获取“id”键的值:
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' ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.