<p><strong>新答案</strong>:</p>
<p>根据<code>a_dict</code>中的值更新<code>alist</code>。</p>
<pre><code>>>> 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`
</code></pre>
<p>驱动程序值</p>
<pre><code>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'}]
</code></pre>
<hr/>
<p><strong>旧答案</strong>:(未完全符合要求)</p>
<p>计算<code>a_dict</code>:</p>
<pre><code>>>> 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']
})
</code></pre>
<p>计算<code>ans_list</code>:</p>
<pre><code>>>> 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'}]
</code></pre>