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']}]
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With