首页 > 解决方案 > How to convert list of list into dictionary object?

问题描述

I have a list of lists that looks like this:

[[['1',
    '1@1`']],
  [['2', '2@2.com']],
  [['3', '3@3.com']],
  [['4', '4@4.com']],
  [['5', '5@5.com']],
  [['6', '6@6']],
  [['7', '7@7']],
  [['8', '8@8']],
  [['8.5', '8.5@8.5']],
  [['9', '9@9']],
  [['10', '10@10']],
  [['11', '11@11']],
  [['12', '12@12']],
  [['13', '13@13.com']],
  [['14', '14@14.com']],
  [['15', '15@15.com']],
  [['16', '16@16.com']],
  [['17', '17@17.com']],
  [['18@18.com', '18']],
  [['19', '19@19.com']]]

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:2@2.com}]

Ideally if there are any emails in the id spot they flipped to the email spot?

标签: python-3.xlistdictionary

解决方案


You can use a list comprehension:

In [1]: mylist = [[['1',
   ...:     '1@1`']],
   ...:   [['2', '2@2.com']],
   ...:   [['3', '3@3.com']],
   ...:   [['4', '4@4.com']],
   ...:   [['5', '5@5.com']],
   ...:   [['6', '6@6']],
   ...:   [['7', '7@7']],
   ...:   [['8', '8@8']],
   ...:   [['8.5', '8.5@8.5']],
   ...:   [['9', '9@9']],
   ...:   [['10', '10@10']],
   ...:   [['11', '11@11']],
   ...:   [['12', '12@12']],
   ...:   [['13', '13@13.com']],
   ...:   [['14', '14@14.com']],
   ...:   [['15', '15@15.com']],
   ...:   [['16', '16@16.com']],
   ...:   [['17', '17@17.com']],
   ...:   [['18@18.com', '18']],
   ...:   [['19', '19@19.com']]]

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': '2@2.com'},
 {'id': '3', 'email': '3@3.com'},
 {'id': '4', 'email': '4@4.com'},
 {'id': '5', 'email': '5@5.com'},
 {'id': '6', 'email': '6@6'},
 {'id': '7', 'email': '7@7'},
 {'id': '8', 'email': '8@8'},
 {'id': '8.5', 'email': '8.5@8.5'},
 {'id': '9', 'email': '9@9'},
 {'id': '10', 'email': '10@10'},
 {'id': '11', 'email': '11@11'},
 {'id': '12', 'email': '12@12'},
 {'id': '13', 'email': '13@13.com'},
 {'id': '14', 'email': '14@14.com'},
 {'id': '15', 'email': '15@15.com'},
 {'id': '16', 'email': '16@16.com'},
 {'id': '17', 'email': '17@17.com'},
 {'id': '18', 'email': '18@18.com'},
 {'id': '19', 'email': '19@19.com'}]

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))]

推荐阅读