I have a dictionary like this
x={6:{"Apple","Banana","Tomato"},9:{"Cake"},11:{"Pineapple","Apple"}}
and I want to add a missed number as keys and empty string as values like this
x={1:"",2:"",3:"",4:"",5:"",6:{"Apple","Banana","Tomato"},7:"",8:"",9:{"Cake"},10:"",11:{"Pineapple","Apple"}}
What should I do? Thank you in advanced
CodePudding user response:
Build a new dict with a comprehension:
>>> x={6:{"Apple","Banana","Tomato"},9:{"Cake"},11:{"Pineapple","Apple"}}
>>> x = {k: x.get(k, "") for k in range(1, max(x) 1)}
>>> x
{1: '', 2: '', 3: '', 4: '', 5: '', 6: {'Banana', 'Tomato', 'Apple'}, 7: '', 8: '', 9: {'Cake'}, 10: '', 11: {'Apple', 'Pineapple'}}
Depending on your use case, you might also find defaultdict
useful, e.g.:
>>> from collections import defaultdict
>>> x = defaultdict(str)
>>> x.update({6:{"Apple","Banana","Tomato"},9:{"Cake"},11:{"Pineapple","Apple"}})
>>> x[6]
{'Banana', 'Tomato', 'Apple'}
>>> x[1]
''
The idea with defaultdict
is that any key you try to access will provide the default (in this case str()
) if no other value has been set -- there's no need to go and fill in the "missing" values ahead of time because the dictionary will just supply them as needed. The case where this wouldn't work would be if you needed to iterate over the entire dictionary and have those empty values be included.
CodePudding user response:
Loop over the numbers from 0 to 11. If a number is not found in the dictionary, add it.
for n in range(12):
if n not in x:
x[n] = ""
CodePudding user response:
You can build your dictionary using dict.fromkeys
then update that dict with x
.
out = {**dict.fromkeys(range(1, max(x) 1), ""), **x}
Output:
{1: '', 2: '', 3: '', 4: '', 5: '', 6: {'Tomato', 'Apple', 'Banana'},
7: '', 8: '', 9: {'Cake'}, 10: '', 11: {'Apple', 'Pineapple'}}
dict.fromkeys(iterable, value=None)
docs string:
Create a new dictionary with keys from
iterable
and values set tovalue
.
dict.fromkeys(range(1, max(x) 1), "")
# {1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: '', 10: '', 11: ''}
And we can merge two dicts using {**x, **y}
. Check out : Merge two dictionaries in python