Reputation: 3667
I have a list of lists that looks like this:
[[['1',
'1@1`']],
[['2', '[email protected]']],
[['3', '[email protected]']],
[['4', '[email protected]']],
[['5', '[email protected]']],
[['6', '6@6']],
[['7', '7@7']],
[['8', '8@8']],
[['8.5', '[email protected]']],
[['9', '9@9']],
[['10', '10@10']],
[['11', '11@11']],
[['12', '12@12']],
[['13', '[email protected]']],
[['14', '[email protected]']],
[['15', '[email protected]']],
[['16', '[email protected]']],
[['17', '[email protected]']],
[['[email protected]', '18']],
[['19', '[email protected]']]]
is there anyway I can clean up the list by making it into a dictionary object like so:
[{id:1,email:1@1},{id:2,email:[email protected]}]
Ideally if there are any emails in the id
spot they flipped to the email
spot?
Upvotes: 0
Views: 48
Reputation: 16593
You can use a list comprehension:
In [1]: mylist = [[['1',
...: '1@1`']],
...: [['2', '[email protected]']],
...: [['3', '[email protected]']],
...: [['4', '[email protected]']],
...: [['5', '[email protected]']],
...: [['6', '6@6']],
...: [['7', '7@7']],
...: [['8', '8@8']],
...: [['8.5', '[email protected]']],
...: [['9', '9@9']],
...: [['10', '10@10']],
...: [['11', '11@11']],
...: [['12', '12@12']],
...: [['13', '[email protected]']],
...: [['14', '[email protected]']],
...: [['15', '[email protected]']],
...: [['16', '[email protected]']],
...: [['17', '[email protected]']],
...: [['[email protected]', '18']],
...: [['19', '[email protected]']]]
In [2]: [{'id': i, 'email': e} for i, e in (pair[0] if '@' not in pair[0][0] else reversed(pair[0]) for pair in mylist)]
Out[2]:
[{'id': '1', 'email': '1@1`'},
{'id': '2', 'email': '[email protected]'},
{'id': '3', 'email': '[email protected]'},
{'id': '4', 'email': '[email protected]'},
{'id': '5', 'email': '[email protected]'},
{'id': '6', 'email': '6@6'},
{'id': '7', 'email': '7@7'},
{'id': '8', 'email': '8@8'},
{'id': '8.5', 'email': '[email protected]'},
{'id': '9', 'email': '9@9'},
{'id': '10', 'email': '10@10'},
{'id': '11', 'email': '11@11'},
{'id': '12', 'email': '12@12'},
{'id': '13', 'email': '[email protected]'},
{'id': '14', 'email': '[email protected]'},
{'id': '15', 'email': '[email protected]'},
{'id': '16', 'email': '[email protected]'},
{'id': '17', 'email': '[email protected]'},
{'id': '18', 'email': '[email protected]'},
{'id': '19', 'email': '[email protected]'}]
If you have arbitrary nesting, you can try this:
def flatten(lst):
for sub in lst:
if isinstance(sub, list):
yield from flatten(sub)
else:
yield sub
[{'id': i, 'email': e} for i, e in (pair if '@' not in pair[0] else reversed(pair) for pair in zip(*[flatten(mylist)]*2))]
Upvotes: 2