[英]Convert list to dictionary of tuples based on column value
I'm trying to convert the following lists in Python: 我正在尝试在Python中转换以下列表:
headers = [ 'Col1','Col2','Col3','Col4' ]
data = [[ '1','A','D','X']
[ '2','A','D','X']
[ '3','A','C','X']
[ '1','B','F','X']
[ '2','B','F','X'] ]
to a dictionary of tuples with the Col2 used as the unique key so the output would like like below: 到使用Col2作为唯一键的元组字典,所以输出如下所示:
{
'A': [( '1','D','X'),('2','D','X'),('3','C','X') ]
'B': [( '1','F','X'),('2','F','X') ]
}
So far I've managed to transpose and zip it to a dictionary with columns as keys but I stucked there. 到目前为止,我已设法将其转置并将其压缩到一个字典作为键,但我坚持到那里。
transpose_result = map(list, zip(*data))
data = dict(zip(headers, transpose_result))
Can you help? 你能帮我吗? Thanks in advance.
提前致谢。
Iterate the data
list items, and build new dictionary with row[1]
as a key and row[:1] + row[2:]
for values (list items): 迭代
data
列表项,并使用row[1]
作为键构建新字典,并为row[:1] + row[2:]
(列表项) row[:1] + row[2:]
:
>>> data = [
... ['1','A','D','X'],
... ['2','A','D','X'],
... ['3','A','C','X'],
... ['1','B','F','X'],
... ['2','B','F','X'],
... ]
>>> d = {}
>>> for row in data:
... d.setdefault(row[1], []).append(row[:1] + row[2:])
...
>>> d
{'B': [['1', 'F', 'X'], ['2', 'F', 'X']],
'A': [['1', 'D', 'X'], ['2', 'D', 'X'], ['3', 'C', 'X']]}
dict.setdefault
is used to populate the dictionary with a empty list when there's no key in the dictionary, so the list.append
call can be done safely. 当字典中没有键时,
dict.setdefault
用于使用空列表填充字典,因此可以安全地完成list.append
调用。
If you use collections.defaultdict
, it could be simpler: 如果您使用
collections.defaultdict
,它可能更简单:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for row in data:
... d[row[1]].append(row[:1] + row[2:])
...
>>> d
defaultdict(<type 'list'>, {
'A': [['1', 'D', 'X'], ['2', 'D', 'X'], ['3', 'C', 'X']],
'B': [['1', 'F', 'X'], ['2', 'F', 'X']]})
>>> dict(d) # to convert it back to dict
{'A': [['1', 'D', 'X'], ['2', 'D', 'X'], ['3', 'C', 'X']],
'B': [['1', 'F', 'X'], ['2', 'F', 'X']]}
Hope this helps.. 希望这可以帮助..
data = [[ '1','A','D','X'],
[ '2','A','D','X'],
[ '3','A','C','X'],
[ '1','B','F','X'],
[ '2','B','F','X'] ]
res = {}
for d in data:
key = d[1]
d.remove(key)
if key in res.keys():
res[key].append(d)
else:
res[key] = [d]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.