Home > Software engineering >  How to combine a list into 1 dict in Python
How to combine a list into 1 dict in Python

Time:09-22

I have a list like this:

List A = {'serial': '8BQZ-CCSU-XY36'}, {'serial': 'IEAJ-NVIS-VMKM'}, {'serial': '1ZQN-FXHB-FTXT'}]

Since I need to send it over my Django html template, how can I make it to a dict ? Other than that, it also require the key serial to be different for every value because dict doesnt accept duplicate keys.

So my idea was making my List A to dict that have different keys name like serial1, serial2,serial3 (depend on how many data user input.)

So my question is how can I make my List A to a dict and iterate the serial key based on how many input?

Expected Output:

List A = {'serial1': '8BQZ-CCSU-XY36', 'serial2': 'IEAJ-NVIS-VMKM', 'serial3': '1ZQN-FXHB-FTXT'}]

CodePudding user response:

You can use a dictionary comprehension:

{k str(i 1): v for i,d in enumerate(List_A) for k,v in d.items()}

output:

{'serial1': '8BQZ-CCSU-XY36',
 'serial2': 'IEAJ-NVIS-VMKM',
 'serial3': '1ZQN-FXHB-FTXT'}

input:

List_A = [{'serial': '8BQZ-CCSU-XY36'},
          {'serial': 'IEAJ-NVIS-VMKM'},
          {'serial': '1ZQN-FXHB-FTXT'}]

CodePudding user response:

dic = {}
for j, i in enumerate(listA):
    j = j 1
    for key,val in i.items():
        dic[key j] = val
  • Related