EB2127
EB2127

Reputation: 1858

How to generate a list of dictionaries from a list of keys and the same value

I would like to create a list of dicts from a list of keys and with the same value for each dict.

The structure would be:

[{key1: value}, {key2: value}, {key3: value}, ...]

I begin with a list of keys:

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

Let's say the value would be ['dog', 'cat'].

Here is what the final result should look like:

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

Upvotes: 5

Views: 2522

Answers (4)

martineau
martineau

Reputation: 123433

You could use a collections.defaultdict dictionary subclass to make the 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 going to do is append those two items to each entry, it would be slightly more efficient to do both in a single operation like the following:

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

Upvotes: 2

Aaditya Ura
Aaditya Ura

Reputation: 12669

You don't need to remove , Without importing any external module or without making it too complex 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']}

Upvotes: 2

uskysd
uskysd

Reputation: 103

If you want to use list comprehension with different values for each keys.

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']}]

Upvotes: 2

RoadRunner
RoadRunner

Reputation: 26315

If you want something really simple, you can use a 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']}]

Additionally, here is an example of adding/removing values with the very convienient 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)

Which outputs:

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

Using a defaultdict here is helpful, as it initializes each entry in the dictionary with an empty list. If you don't want to do this, you could achieve this with a normal dictionary, as shown in your question, but this requires you to initialize the empty lists yourself.

Upvotes: 6

Related Questions