Create a dictionary from keylists and multiple values

I have two lists:

header = ["Name", "Age"] detail = ["Joe", 22, "Dave", 43, "Herb", 32] 

And I would like to create a list such as:

 [{"Name": "Joe", "Age": 22}, {"Name": "Dave", "Age": 32}, {"Name": "Herb", "Age": 32}] 

This zip method gets me partially there, but only adds the first set of values โ€‹โ€‹to the dictionary:

 >>> dict(zip(header, detail)) {'Age': 22, 'Name': 'Joe'} 

How can I output as one dictionary for all values โ€‹โ€‹in the detail list? I found this answer , but it depends on the detail containing the nested lists.

+4
source share
4 answers

For such tasks, I prefer a functional approach.

Here is the recipe for the group:

 def grouper(n, iterable, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) 

Using this, we can move through detail groups 2 :

 >>> groups = grouper(len(header),detail) >>> list(groups) [('Joe', 22), ('Dave', 43), ('Herb', 32)] 

And then we can use this iterator to create dictionaries as needed:

 >>> [dict(zip(header,group)) for group in groups] [{'Age': 22, 'Name': 'Joe'}, {'Age': 43, 'Name': 'Dave'}, {'Age': 32, 'Name': 'Herb'}] 

To clarify, zip(header,group) gives the following:

 >>> zip(["Name", "Age"],('Joe', 22)) [('Name', 'Joe'), ('Age', 22)] 

And calling the dict constructor gives the following:

 >>> dict([('Name', 'Joe'), ('Age', 22)]) {'Age': 22, 'Name': 'Joe'} 
+2
source
 >>> detail = ["Joe", 22, "Dave", 43, "Herb", 32] >>> d = dict(zip(detail[::2], detail[1::2])) >>> d {'Herb': 32, 'Dave': 43, 'Joe': 22} 

For your new / editable question:

 >>> d = [dict(zip(header, items)) for items in zip(detail[::2],detail[1::2])] >>> d [{'Age': 22, 'Name': 'Joe'}, {'Age': 43, 'Name': 'Dave'}, {'Age': 32, 'Name': 'H erb'}] 
+7
source

Here is one way to get it:

 header = ["Name", "Age"] detail = ["Joe", 22, "Dave", 43, "Herb", 32] data_iter = iter(detail) collated = [] while True: next_data = zip(header, data_iter) if not next_data: break collated.append(dict(next_data)) 

output

 [{'Age': 22, 'Name': 'Joe'}, {'Age': 43, 'Name': 'Dave'}, {'Age': 32, 'Name': 'Herb'}] 

This version has the advantage that you do not need to change the code if you change the number of headers.

+2
source
 >>> header = ["Name", "Age"] >>> detail = ["Joe", 22, "Dave", 43, "Herb", 32] >>> [dict(zip(header,detail[i:i+2])) for i in range(0,len(detail),2)] [{'Age': 22, 'Name': 'Joe'}, {'Age': 43, 'Name': 'Dave'}, {'Age': 32, 'Name': 'Herb'}]` 
+1
source

Source: https://habr.com/ru/post/1437399/


All Articles