Home > OS >  convert list of list to dictionary with some key pattern
convert list of list to dictionary with some key pattern

Time:12-01

I am looking to convert a list of lists which contains some details in the below format into a dictionary.

[['1234567890', 'abcdef', 'xyzd'],
 ['0987654321', 'pqrstuvw', 'oiu'],
 ['6767547879', 'djkaddsd', 'dsad']]

I want it to be in the below format.

{'target0': ['1234567890', 'abcdef', 'xyzd'],
 'target1': ['0987654321', 'pqrstuvw', 'oiu'],
 'target2': ['6767547879', 'djkaddsd', 'dsad']}

CodePudding user response:

I'd prefer enumerate in a dictionary comprehension:

>>> {f'target{k}': v for k, v in enumerate(lst)}
{'target0': ['1234567890', 'abcdef', 'xyzd'], 
 'target1': ['0987654321', 'pqrstuvw', 'oiu'], 
 'target2': ['6767547879', 'djkaddsd', 'dsad']}
>>> 

Also I used f-strings.

CodePudding user response:

You can use dict comprehension for a nice one liner :)

output = {'target' str(x):values[x] for x in range(len(values))}

This outputs:

{'target0': ['1234567890', 'abcdef', 'xyzd'],
 'target1': ['0987654321', 'pqrstuvw', 'oiu'],
 'target2': ['6767547879', 'djkaddsd', 'dsad']}
  • Related