0

the dictionary sample is as below :

d = { 1:'',2:'',3:'',5:'',6:'2',7:'',9:'',10:'6',11:'7',13:'9',14:'',15:'11'}

and i want to add key 4 with empty string as value after key 3, key 8 with empty string as value after key 7 and so on ....I want the simplest code in python.

2 Answers 2

5
>>> d = { 1:'',2:'',3:'',5:'',6:'2',7:'',9:'',10:'6',11:'7',13:'9',14:'',15:'11'}
>>> d.update(dict.fromkeys(set(range(16)).difference(d), ''))
>>> d
{0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '2', 7: '', 8: '', 9: '', 10: '6', 11: '7', 12: '', 13: '9', 14: '', 15: '11'}

Note that the dict is unordered, even though it may look ordered in this example!

Sign up to request clarification or add additional context in comments.

1 Comment

@Gnibber Thanks Gnibber, Your answer seems useful for me and I will be using it in my application code.
2

Python dictionaries do not maintain an order. You cannot add anything 'after' another key.

Just add the keys you are missing:

d.update((missing, '') for missing in set(range(1, max(d) + 1)).difference(d))

which is a compact way of saying:

for index in range(1, max(d) + 1):  # all numbers from 1 to the highest value in the dict
    if index not in d:              # index is missing
        d[index] = ''               # add an empty entry

However, it looks more like you need a list instead:

alist = [None, '', '', '', '', '', '2', '', '', '', '6', '7', '', '9', '', '11']

where alist[15] returns '11' just like your d. The None at the start makes it easier to treat this whit 1-based indexing instead of 0-based, you could adjust your code for that otherwise.

5 Comments

I suppose you could also use d.setdefault in your loop as well to avoid the index in d business...
@mgilson: Since the loop is meant to illustrate what the code above it does, I think .setdefault() would only muddle the waters more.
@MartijnPieters It seems that you are generating a list but I need to add my missing keys in the dictionary. The dictionary contains only numeric keys to they can be generated. I think you should take a reference of Above answer.
@RiturajRamteke: That is what my answer does, generate the missing keys. But, a dictionary is an inefficient data structure if you wanted to map integers to values, where those integers are in a contiguous sequence. I am advising you to consider using a list instead.
@RiturajRamteke: the dict.fromkeys() method is slightly more efficient, because indeed all that varies here is the keys, not the value, so in that respect gnibbler's solution is better, for updating your dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.