Home > Net >  Two list to dictionary
Two list to dictionary

Time:12-25

I have two list.

id = [1,2,3]
text = [['a'], ['b'], ['c']]

I need output in dictionary like

[{'ID':1,'TEXT':['a']},{'ID':2,'TEXT':['b']},{'ID':3,'TEXT':['c']}]

I tried something by zipping two list, I'm not able to reach this ouput

CodePudding user response:

you mean to build dictionaries for each zipped couple of id (note: this is a reserved function in python) and text

result = [{'ID':k,'TEXT':v} for k,v in zip(id,text)]

>>> result
[{'ID': 1, 'TEXT': ['a']}, {'ID': 2, 'TEXT': ['b']}, {'ID': 3, 'TEXT': ['c']}]

CodePudding user response:

The zip() function takes 2 "iterables" and compacts them into one ->

out = []
for e in zip([1,2,3], [['a'], ['b'], ['c']]):
    out.append({'ID': e[0], 'TEXT': e[1]})

or list comprehension ->

out = [{'ID': e[0], 'TEXT': e[1]} for e in zip([1,2,3], [['a'], ['b'], ['c']])]

CodePudding user response:

Assuming the lists are always the same length, you can just walk over them, constructing a dict with each element. No need to use zip to construct an 'intermediate' list:


iid = [1,2,3]
text = [['a'], ['b'], ['c']]
out = []
for i in range(len(iid)):
    out.append({'ID': iid[i], 'TEXT': text[i]})
print(out)
  • Related