[英]python to update dict values in list
I have a list with two element (key-value pair)in it. 我有一个包含两个元素(键值对)的列表。 Both element has same keys in it. 两个元素都有相同的键。 however few values are different, shown as below. 但是很少有不同的值,如下所示。
alist = [{u'a': u'x', u'b': u'y', u'c': u'z'}, {u'a': u'x', u'b': u'm', u'c': u'n'}]
I want to update new data to alist from available in dictionary, which is update from user input, shown below. 我想更新新数据,从字典中可用,这是从用户输入更新,如下所示。
a_dict = {'a': ['user_input_x'], 'b': ['user_input_y', 'user_input_m'], 'c': ['user_input_z', 'user_input_n']}
Resultant alist should look like this, 结果alist应该是这样的,
ans_alist = [{u'a': u'user_input_x', u'b': u'user_input_y', u'c': u'user_input_z'}, {u'a': u'user_input_x', u'b': u'user_input_m', u'c': u'user_input_n'}]
I was trying out few things, below is the snippet, however since it's dict, code is updating all the keys, with same values, 我正在尝试一些事情,下面是片段,但是因为它是dict,代码正在更新所有键,具有相同的值,
for i in range(0, 2):
for key in alist:
key['a'] = a_dict['a'][i]
key['b'] = a_dict['b'][i]
key['c'] = a_dict['b'][i]
print alist
ans_alist = [{u'a': ['user_input_x'], u'b': 'user_input_y', u'c': 'user_input_n'}, {u'a': ['user_input_x'], u'b': 'user_input_y', u'c': 'user_input_n'}]
appreciate your help. 感谢您的帮助。
New Answer : 新答案 :
Update alist
according to the values in a_dict
. 根据a_dict
的值更新alist
。
>>> new_alist = []
>>> for i,d in enumerate(alist): #traverse the list
temp = {}
for key,val in d.items(): #go through the `dict`
if len(a_dict[key])>0 : #alist->[key] is present in a_dict
temp[key] = a_dict[key].pop(0) #used the value, delete it from a_dict
else : #use previous updated value
temp[key] = new_alist[i-1][key] #get value from previously updated
new_alist.append(temp) #add the updated `dict`
#driver values #driver值
IN : alist = [{u'a': u'x', u'b': u'y', u'c': u'z'},
{u'a': u'x', u'b': u'm', u'c': u'n'}]
IN : a_dict = {'a': ['user_input_x'], 'b': ['user_input_y', 'user_input_m'], 'c': ['user_input_z', 'user_input_n']}
OUT : new_alist
=> [{'a': 'user_input_x', 'b': 'user_input_y', 'c': 'user_input_z'},
{'a': 'user_input_x', 'b': 'user_input_m', 'c': 'user_input_n'}]
Old Answer : (wasn't according to requirements fully) 旧答案 :(完全不符合要求)
Compute a_dict
: 计算a_dict
:
>>> from collections import defaultdict
>>> a_dict = defaultdict(list)
>>> for d in alist: #traverse the list
for key,val in d.items():
if val not in a_dict[key]: #if val not already there
a_dict[key].append(val) #add it to the [key]
>>> a_dict
=> defaultdict(<class 'list'>,
{'a': ['user_input_x'],
'b': ['user_input_y', 'user_input_m'],
'c': ['user_input_z', 'user_input_n']
})
Compute ans_list
: 计算ans_list
:
>>> ans_list = []
>>> for d in alist: #traverse the list
temp = {}
for key,val in d.items():
temp[key] = val
ans_list.append(temp) #add the new dictionary
>>> ans_list
=> [{'a': 'user_input_x', 'b': 'user_input_y', 'c': 'user_input_z'},
{'a': 'user_input_x', 'b': 'user_input_m', 'c': 'user_input_n'}]
Another alternative way would be: 另一种替代方式是:
from collections import defaultdict
repeat_count = len(alist)
ans_alist = [defaultdict(dict) for _ in range(repeat_count)]
for k, v in a_dict.items():
mul_times = repeat_count / len(v) # Use // if Python 3
extend_counter = repeat_count % (mul_times * len(v))
repeat_v = v * mul_times + v[:extend_counter]
unicode_k = u'{}'.format(k)
for index, val in enumerate(repeat_v):
ans_alist[index][unicode_k] = u'{}'.format(val)
You need to iterate over the list of dicts, grab one dict at a time. 你需要遍历dicts列表,一次抓取一个dict。 Then iterate over its keys and pop the items from the result list: 然后遍历其键并弹出结果列表中的项:
new_alist = []
for d in alist:
new_dict = {}
for k in d.keys():
if a_dict[k]:
new_dict[k] = a_dict[k].pop(0)
new_alist.append(new_dict)
>>> new_alist
[{u'a': 'user_input_x', u'c': 'user_input_z', u'b': 'user_input_y'}, {u'c':
'user_input_n', u'b': 'user_input_m'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.