res[0]={'k3':org_dict[k3][0],'k2':org_dict[k2][0],'k1':org_dict[k1][0]}
#res[0] value pos is in filter_data:[0,0,0]
res[1]={'k3':org_dict[k3][0],'k2':org_dict[k2][1],'k1':org_dict[k1][1]}
#res[1] value pos is in filter_data:[0,1,1]
res[2]={'k3':org_dict[k3][1],'k2':org_dict[k2][0],'k1':org_dict[k1][1]}
#res[2] value pos is in filter_data:[1,0,1]
期待结果:
res=[{'k3': 5, 'k2': 3, 'k1': 1},{'k3': 5, 'k2': 2, 'k1': 2},...]
...
例如:
dataType:'JSON'
非常感谢!!!
答案 0 :(得分:1)
使用有序词典:
import collections
d = collections.OrderedDict([('k3',[5, 6]), ('k2', [3, 2]), ('k1',[1, 2])])
f_data = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]]
迭代过滤器;在循环的顶部创建一个新的空字典;使用zip将过滤器中的索引与目标字典中的项相关联并迭代;将带有过滤值的item键添加到新词典中。
for f in f_data:
q = collections.OrderedDict()
for index, (k, v) in zip(f, d.items()):
q[k] = v[index]
print(q)
>>>
OrderedDict([('k3', 5), ('k2', 3), ('k1', 1)])
OrderedDict([('k3', 5), ('k2', 2), ('k1', 2)])
OrderedDict([('k3', 6), ('k2', 3), ('k1', 2)])
OrderedDict([('k3', 6), ('k2', 2), ('k1', 1)])
>>>
使用普通字典,您需要一个序列来将键与过滤器匹配:
f_data = [[ 0 , 0 , 0 ], [ 0 , 1 , 1 ], [ 1 , 0 , 1 ], [ 1 , 1 , 0 ]]
| | | | | | | | | | | |
'k3' 'k2' 'k1' 'k3' 'k2' 'k1' 'k3' 'k2' 'k1' 'k3' 'k2' 'k1'
d = dict([('k3',[5, 6]), ('k2', [3, 2]), ('k1',[1, 2])])
key_order = ['k3', 'k2', 'k1']
for f in f_data:
q = dict()
for index, key in zip(f, key_order):
q[key] = d[key][index]
print(q)
>>>
{'k3': 5, 'k2': 3, 'k1': 1}
{'k3': 5, 'k2': 2, 'k1': 2}
{'k3': 6, 'k2': 3, 'k1': 2}
{'k3': 6, 'k2': 2, 'k1': 1}
>>>