[英]Python list of dictionary append value to different keys
假設我有這個包含字典的列表:
In [5]: m
Out[5]: [{0: ['a', 'b'], 1: '1', 2: '2'},
{0: ['a', 'b'], 1: '3', 2: '4'},
{0: ['xx', 'yy'], 1: '100', 2: '200'},
{0: ['xx', 'yy'], 1: '300', 2: '400'}]
我這樣做:
In [6]: r = defaultdict(list)
In [7]: for k, v in ((k, v) for row in m for k, v in row.iteritems()):
r[k].append(v)
它返回:
In [8]: r
Out[8]: defaultdict(list,
{0: [['a', 'b'], ['a', 'b'], ['xx', 'yy'], ['xx', 'yy']],
1: ['1', '3', '100', '300'],
2: ['2', '4', '200', '400']})
但我想要其他的東西,像這樣:
{0: ['a', 'b'],
1: ['1', '3'],
2: ['2', '4']},
{0: ['xx', 'yy'],
1: ['100', '300'],
2: ['200', '400']}
我怎樣才能做到這一點? 我想在鍵 0 中取相同的值並收集它們在其他鍵中找到的所有其他值。
非常感謝!
Step 1 - 先拆分字典,否則不清楚自動拆分的邏輯是什么。 第 2 步 - 遍歷字典列表並應用一些 if 語句。 這是我認為它應該是什么樣子。 希望我有正確的邏輯:
d = [{0: ['1', '2'], 1: '3', 2: '4'},
{0: ['1', '2'], 1: '6', 2: '7'},
{0: ['1111', '2222'], 1: '6', 2: '7'},
{0: ['1111', '2222'], 1: '66', 2: '77'}
]
#step 1
def splitList(l, n):
"""
takes list and positions to take from the list
"""
output = []
for p in n:
output.append(l[p])
return output
#step 2
def orgDict(d):
"""
modifies list of dictionaries into 1
"""
d_output = {}
for d_ind in d:
for d_ind2 in d_ind:
if (d_output.get(d_ind2) == None):
if (type(d_ind[d_ind2]) == list):
d_output[d_ind2] = d_ind[d_ind2]
else:
d_output[d_ind2] = [d_ind[d_ind2]]
else:
if ((d_ind[d_ind2] not in d_output[d_ind2]) and (d_ind[d_ind2] != d_output[d_ind2])):
d_output[d_ind2].append(d_ind[d_ind2])
return d_output
#tests
#expected output:
#{0: ['1', '2'], 1: ['3', '6'], 2: ['4', '7']}
print orgDict(splitList(d,[0,1]))
#expected output:
#{0: ['1111', '2222'], 1: ['6', '66'], 2: ['7', '77']}
print orgDict(splitList(d,[2,3]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.