Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']}]
like image 584
EB2127 Avatar asked Dec 15 '17 02:12

EB2127


People also ask

How do you create a dictionary from a list of keys and values?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.

How do you get a list of all the keys in a dictionary?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.


1 Answers

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.

like image 130
RoadRunner Avatar answered Nov 15 '22 03:11

RoadRunner