Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

>>> CRS = [{b[i]: v for i, v inenumerate(x)} for x inzip(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'}]

Solution 2:

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'}]

Post a Comment for "Converting Lists To List Of Dictionaries"