简体   繁体   中英

Converting lists to list of dictionaries

I have the following five lists:

a = ['RA CROXE-14156', 'RA CROXE-14084', ]
b = ['CR','ENGINEER_NAME','DESCRIPTION','BINARIES']
c = ['John', 'Mark']
d = ['M4 Hiding Emergency Group from mgr menu', 'M4-NRT: SQLCODE_-11300', ]
e = ['TEL', 'mao.SYM']

I need to create a list of dictionaries like this:

CRS = [
{
      'CR': 'RA CROXE-14156'
      'ENGINEER_NAME': 'John', 
      'DESCRIPTION': 'M4 Hiding Emergency Group from mgr menu',
      'BINARIES': 'TEL'
},
{  
      'CR': 'RA CROXE-14084'
      'ENGINEER_NAME': 'MARK', 
      'DESCRIPTION': 'M4-NRT: SQLCODE_-11300', 
      'BINARIES': 'mao.SYM'
}
]

I need to convert the five lists to a list of dictionaries. How can I do this?

You can use the following list/dict comprehensions, using zip() and enumerate() :

>>> CRS = [{b[i]: v for i, v in enumerate(x)} for x in zip(a,c,d,e)]
>>> CRS
[{'CR': 'RA CROXE-14156',
  'ENGINEER_NAME': 'John',
  'DESCRIPTION': 'M4 Hiding Emergency Group from mgr menu',
  'BINARIES': 'TEL'},
 {'CR': 'RA CROXE-14084',
  'ENGINEER_NAME': 'Mark',
  'DESCRIPTION': 'M4-NRT: SQLCODE_-11300',
  'BINARIES': 'mao.SYM'}]

You can use zip with dict :

a = ['RA CROXE-14156', 'RA CROXE-14084', ]
b = ['CR','ENGINEER_NAME','DESCRIPTION','BINARIES']
c = ['John', 'Mark']
d = ['M4 Hiding Emergency Group from mgr menu', 'M4-NRT: SQLCODE_-11300', ]
e = ['TEL', 'mao.SYM']
result = [dict(zip(b, i)) for i in zip(a, c, d, e)]

Output:

[{'CR': 'RA CROXE-14156', 'ENGINEER_NAME': 'John', 'DESCRIPTION': 'M4 Hiding Emergency Group from mgr menu', 'BINARIES': 'TEL'}, {'CR': 'RA CROXE-14084', 'ENGINEER_NAME': 'Mark', 'DESCRIPTION': 'M4-NRT: SQLCODE_-11300', 'BINARIES': 'mao.SYM'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM