2

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

3 Answers3

3

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.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • with `defaultdict` you could directly do `x = defaultdict(str, x)`(where `x` is OP's original dict) avoiding `.update`. – Ch3steR Dec 03 '21 at 16:05
  • I'm thinking more than you'd just make `x` a defaultdict in the first place, rather than building `x` as a plain dict and then doing a switcheroo later. i.e. if there's an `x = {}` somewhere earlier in the code, make *that* `x = defaultdict(str)` and then there's a good chance that whatever OP is trying to fix with this question just is no longer a problem. – Samwise Dec 03 '21 at 16:12
  • Got it. Makes more sense. – Ch3steR Dec 03 '21 at 16:15
1

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 to value.

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

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
0

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] = ""
John Gordon
  • 29,573
  • 7
  • 33
  • 58