gpt4 book ai didi

python - 如何从列表项制作嵌套字典?

转载 作者:太空狗 更新时间:2023-10-30 02:20:25 25 4
gpt4 key购买 nike

我有一个列表列表,例如:

a = [
['A', 'America', 'LA', '1123', '2014-05-01', [('A', '211'), ('AD', '398')]],
['D', 'America', 'LA', '1135', '2014-05-01', [('A', '211'), ('AD', '398')]],
['I', 'America', 'SF', '1145', '2014-05-01', [('A', '211'), ('AD', '398')]],
['A', 'England', 'LND', '3564', '2014-05-01', [('A', '211'), ('AD', '398')]],
['D', 'Dubai', 'DUB', '9990', '2014-05-01', [('A', '211'), ('AD', '398')]],
['D', 'Dubai', 'DUX', '9670', '2014-05-01', [('A', '211'), ('AD', '398')]],
['I', 'Dubai', 'DUB', '9800', '2014-05-01', [('A', '211'), ('AD', '398')]],
]

我想要一个像这样的嵌套字典:

d = {
'America': {
'LA': {
'1123' : ['A', '2014-05-01', [('A', '211'), ('AD', '398')]],
'1135': ['D', '2014-05-01', [('A', '211'), ('AD', '398')]]
},
'SF': {
'1145': ['I', '2014-05-01', [('A', '211'), ('AD', '398')]]
}
},
'England': {
'LND': {
'3564': ['A', '2014-05-01', [('A', '211'), ('AD', '398')]]
}

},
'Dubai': {
'DUB': {
'9990': ['D', '2014-05-01', [('A', '211'), ('AD', '398')]],
'9800': ['I', '2014-05-01', [('A', '211'), ('AD', '398')]]
},
'DUX': {
'9670': ['D', '2014-05-01', [('A', '211'), ('AD', '398')]]
}
}
}

我试过了还是不行,请检查我的代码并帮助我!

pd = defaultdict(dict)
for row in a:
country = defaultdict(dict)
for c in a:
dest = defaultdict(list)
for d in a:
if c[2] == d[2]:
dest[d[3]].append([d[1], d[0],d[4],d[5],d[6], d[7]])
else:
continue
country[c[2]] = dest
pd[row[1]] = country

最佳答案

from operator import itemgetter
from itertools import groupby
getter, d = itemgetter(0, 4, 5), {}
for key, grp in groupby(sorted(a, key=lambda x: x[3]), key=lambda x: x[3]):
for item in grp:
d.setdefault(item[1], {}).setdefault(
item[2], {})[item[3]] = list(getter(item))
print d

输出

{'America': {'LA': {'1123': ['A',
'2014-05-01',
[('A', '211'), ('AD', '398')]],
'1135': ['D',
'2014-05-01',
[('A', '211'), ('AD', '398')]]},
'SF': {'1145': ['I',
'2014-05-01',
[('A', '211'), ('AD', '398')]]}},
'Dubai': {'DUB': {'9800': ['I',
'2014-05-01',
[('A', '211'), ('AD', '398')]],
'9990': ['D',
'2014-05-01',
[('A', '211'), ('AD', '398')]]},
'DUX': {'9670': ['D',
'2014-05-01',
[('A', '211'), ('AD', '398')]]}},
'England': {'LND': {'3564': ['A',
'2014-05-01',
[('A', '211'), ('AD', '398')]]}}}

关于python - 如何从列表项制作嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23365832/

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