[英]Assign values to a key in a dictionary python
Since I wanted to append a new ID to a dictionary key, I created a new dictionary, based on the old dictionary key plus the new item.由于我想将新 ID 附加到字典键,因此我根据旧字典键和新项创建了一个新字典。 But now, I want to assign for each key of the new dictionary a value of a list.但是现在,我想为新字典的每个键分配一个列表值。
So, I wrote this code:所以,我写了这段代码:
old_dict={22:[99,4['Dog','Dog.1']],14:[99,8['Dog2','Dog.3']],23:[97,8['Cat2','Dog.3']]}
new_dict={22|14:[99,4['Dog','Dog.1']],14|25:[99,8['Dog2','Dog.3']],23|5:[97,8['Cat2','Dog.3']]}
list=[[99,4['Dog','Dog.1']],[99,8['Dog2','Dog.3']],[97,8['Cat2','Dog.3']]]
new_dict2 = {}
for values in list:
for old, new in zip(old_dictionary.keys(), new_dictionary.values()):
new_ID = old + '|' + new
new_dict2[new_ID] = values
However, this is repeating the first value of the list, in all the keys of the new dictionary.但是,这是在新字典的所有键中重复列表的第一个值。
Please, how do I correct this error?请问这个错误怎么改?
22|14 is a bitwise OR function. 22|14 是一个按位或函数。 You probably want your leys to be text.你可能希望你的 leys 是文本。 so keep them in quotes "22|14"所以把它们放在引号“22|14”中
Your solution is to split keys and values and then recombine them.您的解决方案是拆分键和值,然后重新组合它们。 It should look like this:它应该是这样的:
keys1, values1 = dict1.items()
keys2, values2 = dict2.items()
new_keys = [str(a)+'|'+str(b) in zip (keys1, keys2)]
new_dict = {k:v for k, v in zip (new_keys, some_new values)}
I solved my problem this way:我这样解决了我的问题:
final_all={}
for old_k,new_k in zip(old_dictionary.keys(),new_dictionary.keys()):
new_ID=str(old_k) + '|' + str(new_k )
final_all[new_ID]=list_values
Thanks for the help谢谢您的帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.