gpt4 book ai didi

python - 将包含元组列表的字典转换为列表

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:22 27 4
gpt4 key购买 nike

假设我有一本具有以下结构的字典:

namedict = {
1880:
[('Mary', 'F', '7065', 1),
('Anna', 'F', '2604', 2),
('John', 'M', '9655', 1)],
1881:
[('Mary', 'F', '8065', 1),
('Anna', 'F', '9604', 2),
('John', 'M', '5655', 1)],
1882:
[('Mary', 'F', '9065', 1),
('Anna', 'F', '9604', 2),
('John', 'M', '5655', 1)]
}

我想转换字典,使数据处于以下列表结构中:

[{(Mary, F): {1880: [7065, 1], 1881: [8065, 1], 1882: [9065, 1]}]
[{(Anna, F): {1880: [2064, 2], 1881: [9604, 2], 1882: [9604, 1]}]...

关于我如何做到这一点有什么建议吗?

最佳答案

据我了解,collections.defaultdict()在这种情况下可以提供帮助:

from collections import defaultdict
from pprint import pprint

namedict = {
1880:
[('Mary', 'F', '7065', 1),
('Anna', 'F', '2604', 2),
('John', 'M', '9655', 1)],
1881:
[('Mary', 'F', '8065', 1),
('Anna', 'F', '9604', 2),
('John', 'M', '5655', 1)],
1882:
[('Mary', 'F', '9065', 1),
('Anna', 'F', '9604', 2),
('John', 'M', '5655', 1)]
}

d = defaultdict(dict)
for key, values in namedict.items():
for name, gender, value1, value2 in values:
d[(name, gender)][key] = [value1, value2]

pprint(dict(d))

打印:

{('Anna', 'F'): {1880: ['2604', 2], 1881: ['9604', 2], 1882: ['9604', 2]},
('John', 'M'): {1880: ['9655', 1], 1881: ['5655', 1], 1882: ['5655', 1]},
('Mary', 'F'): {1880: ['7065', 1], 1881: ['8065', 1], 1882: ['9065', 1]}}

或者,对于 Python3,您可以使用 extended iterable unpacking并使解决方案更加通用:

d = defaultdict(dict)
for key, values in namedict.items():
for name, gender, *values in values:
d[(name, gender)][key] = values

关于python - 将包含元组列表的字典转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37336110/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com