How to generate a list of dictionaries (with list values) from a list?

Iterating over a python list, I would like to create a list of dictionaries in which the meaning of each dictionary is also a list.

The structure will be:

[{key1: [val1, val2]}, {key2: [val3, val4]}, {key3: [val5, val6]}, ...] 

I'll start with a list of integers:

 my_list = [3423, 77813, 12, 153, 1899] 

For each item in the list, this should become a dictionary key. Then I add two elements to the value of the dictionary (which is a list). (Say two points are always “dog” and “cat”)

Here is the final result:

 [{3423:['dog', 'cat']}, {77813:['dog', 'cat']}, {12:['dog', 'cat']}, {153:['dog', 'cat']}, {1899:['dog', 'cat']}] 

My attempt to do this has many problems:

 for i in my_list: d = {} ## create a dictionary 'd' d[i] = [].append('dog') ## or `d[i] = ['dog'].append('cat')` my_list.append(d) ## here is a bug my_list.remove(i) ## remove the item from the list 
  • I do not like what I should call an empty dictionary, and each of them called the same thing (here, d ). Later, I would like to access each of these dictionaries with keys - I do not care about their names.

  • I do not know how it is reasonable to add several elements to the value of a dictionary when it should actually be a list. What if I wanted to add some elements?

  • The mistake is to add the dictionary to the source list and then delete the item. Naturally, this can be solved using the new list:

     new_list = [] for i in my_list: d = {} d[i] = [].append('dog') new_list.append(d) my_list.remove(i) 

but it seems very awkward.

+5
source share
4 answers

If you need something really simple, you can use list comprehension:

 data = ['dog', 'cat'] my_list = [3423, 77813, 12, 153, 1899] result = [{k:data} for k in my_list] print(result) # [{3423: ['dog', 'cat']}, {77813: ['dog', 'cat']}, {12: ['dog', 'cat']}, {153: ['dog', 'cat']}, {1899: ['dog', 'cat']}] 

In addition, here is an example of adding / removing values ​​using a very convenient defaultdict :

 from collections import defaultdict my_list = [3423, 77813, 12, 153, 1899] new_list = [] for number in my_list: # create the defaultdict here d = defaultdict(list) # add some data d[number] += ['dog', 'cat', 'kitten'] # remove some data d[number].remove('kitten') # append dictionary new_list.append(dict(d)) print(new_list) 

What outputs:

 [{3423: ['dog', 'cat']}, {77813: ['dog', 'cat']}, {12: ['dog', 'cat']}, {153: ['dog', 'cat']}, {1899: ['dog', 'cat']}] 

Using defaultdict is useful here because it initializes every entry in a dictionary with an empty list. If you do not want to do this, you can achieve this using a regular dictionary, as shown in your question, but this requires that you initialize empty lists yourself.

+6
source

You can use a subclass of collections.defaultdict to make processing very simple:

 from collections import defaultdict from pprint import pprint my_list = [3423, 77813, 12, 153, 1899] d = defaultdict(list) for i in my_list: d[i].append('dog') d[i].append('cat') d = dict(d) # Convert d into a regular dictionary (optional). pprint(d) 

Output:

 {12: ['dog', 'cat'], 153: ['dog', 'cat'], 1899: ['dog', 'cat'], 3423: ['dog', 'cat'], 77813: ['dog', 'cat']} 

Of course, if all you have to do is add these two elements to each record, it would be a little more efficient to perform both operations in the same operation, for example:

 for i in my_list: d[i].extend(['dog', 'cat']) 
+2
source

If you want to use a list comprehension with different values ​​for each key.

 keys = ['key1', 'key2', 'key3'] values = [['val11', 'val12'], ['val21', 'val22'], ['val31', 'val32']] # This is what you want (if I understood correctly) dlist = [{x:values[i]} for i,x in enumerate(keys)] print(dlist) # When you want to add more dictionary to the list dlist.append({'key4': ['val41', 'val42']}) print(dlist) 

Output:

 [{'key1':['val11','val12']}, {'key2':['val21','val22']}, {'key3':['val31','val32']}] [{'key1':['val11','val12']}, {'key2':['val21','val22']}, {'key3':['val31','val32']}, {'key4':['val41', 'val42']}] 
+2
source

You do not need to delete without importing any external module or making it too complicated. You can simply follow this pattern in pure python:

 data = ['dog', 'cat'] my_list = [3423, 77813, 12, 153, 1899] new_data={} for item in my_list: for sub_item in data: if item not in new_data: new_data[item]=[sub_item] else: new_data[item].append(sub_item) print(new_data) 

output:

 {153: ['dog', 'cat'], 1899: ['dog', 'cat'], 12: ['dog', 'cat'], 77813: ['dog', 'cat'], 3423: ['dog', 'cat']} 
+2
source

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


All Articles