0
key  = ["id","name","sal"]
id   = [1,2,3,4]
info = [["John",1000], ["Joel",5000], ["Tom",2000],["Ray",1000]]

What's the most easy way to generate the below output in python(list of dictionaries)?

[{id=1,name="John",sal=1000},
 {id=2,name="Joel",sal=5000},
 {id=3,name="Tom",sal=2000},
 {id=4,name="Ray",sal=1000}]
Safdar Mirza
  • 89
  • 3
  • 11

4 Answers4

3

You can use zip:

key_list = ['name','id']
name_list = ['John', 'Tom', 'David','Joel','Liza']
id_list = [1,2,3,4,5]
final_data = [{key_list[0]:a, key_list[1]:b} for a, b in zip(name_list, id_list)]

Output:

[{'name': 'John', 'id': 1}, {'name': 'Tom', 'id': 2}, {'name': 'David', 'id': 3}, {'name': 'Joel', 'id': 4}, {'name': 'Liza', 'id': 5}]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • For better performance with `python 2.7` in this problem, you should use `itertools.izip`. – Huu-Danh Pham Nov 09 '17 at 15:03
  • 1
    You can use `zip` again to shorten it (slightly): `[dict(zip(key_list, v)) for v in zip(name_list, id_list)]`. – chepner Nov 09 '17 at 15:04
  • @DanhPham If `name_list` and `id_list` are already fully instantiated lists, using `itertools` will simply add overhead. The functions in `itertools` are for memory efficiency. – chepner Nov 09 '17 at 15:05
  • @chepner you don't need the full list of items constructed in this case, you only need an iterables. `izip` is useful for saving memory. I follow the answers in this question: [When is it better to use zip instead of izip?](https://stackoverflow.com/questions/4989763/when-is-it-better-to-use-zip-instead-of-izip) – Huu-Danh Pham Nov 09 '17 at 15:13
3

You can zip the name and id lists, and zip those tuples again with the key list.

>>> [dict(zip(key_list, pair)) for pair in zip(name_list, id_list)]
[{'name': 'John', 'id': 1},
 {'name': 'Tom', 'id': 2},
 {'name': 'David', 'id': 3},
 {'name': 'Joel', 'id': 4},
 {'name': 'Liza', 'id': 5}]

This also works for arbitrary numbers of keys and attribute-lists.

>>> attributes = [name_list, id_list] # and maybe more
>>> [dict(zip(key_list, pair)) for pair in zip(*attributes)]
tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

You can use zip and combine the name and id lists, and zip those tuples again with the key list. This should work for your requirement,

key_list = ['name', 'id']
name_list = ['John', 'Tom', 'David', 'Joel', 'Liza']
id_list = [1, 2, 3, 4, 5]
data =  [dict(zip(key_list, (a,b))) for a,b in zip(name_list, id_list)]

output should look like,

[{'name': 'John', 'id': 1}, {'name': 'Tom', 'id': 2}, {'name': 'David', 'id': 3}, {'name': 'Joel', 'id': 4}, {'name': 'Liza', 'id': 5}]
Radan
  • 1,630
  • 5
  • 25
  • 38
0

i think my solution is according to output format

[{'{}={}'.format(key_list[0],a),'{}={}'.format(key_list[1],b)} for a, b in zip(name_list, id_list)]

output

 [{'id=1', 'name=John'},
 {'id=2', 'name=Tom'},
 {'id=3', 'name=David'},
 {'id=4', 'name=Joel'},
 {'id=5', 'name=Liza'}]
Argus Malware
  • 773
  • 7
  • 19