I have a list of lists like:
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')]],
]
And I want a nested Dict like:
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')]]
}
}
}
I have tried to make it but still unable to do it, please check my code and help me!
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
Output
{'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')]]}}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With