update values of list in dictionary

Question:

I have a dictionary d = {'1':[2,3,5,6], '4':[1,6,8]}, I want to update the values in the list which are not present in range(1,11), while the key remains same.

The new dictionary should be like:

d1 = {'1':[1, 4, 7, 8, 9, 10], '4':[2, 3, 4, 5, 7, 9, 10]

Please suggest how it can be done.

I have already tried:

d = {'1':[2,3,5,6], '4':[1,6,8]}
x = range(1,17)
dic ={}
l=[]
for k,v in d.items():
    for x in range(1,17):
        if x not in v:
        l.append(x)
    dic[k] = l

Which gives me result as:

{'1': [1, 4, 7, 8, 9, 10, 2, 3, 4, 5, 7, 9, 10], '4': [1, 4, 7, 8, 9, 10, 2, 3, 4, 5, 7, 9, 10]}
Asked By: Mousam Jha

||

Answers:

You can do this with a dict comprehension:

>>> d = {'1':[2,3,5,6], '4':[1,6,8]}
>>> x = range(1, 11)
>>> {k: [i for i in x if i not in v] for k, v in d.items()}
{'1': [1, 4, 7, 8, 9, 10], '4': [2, 3, 4, 5, 7, 9, 10]}
Answered By: sj95126

You only have an issue with the initialization of l, it should be inside the first loop,

d = {'1':[2,3,5,6], '4':[1,6,8]}
dic ={}

for k,v in d.items():
    l = []
    for x in range(1,11):
        if x not in v:
            l.append(x)
    dic[k] = l
print(dic)

OR a single-line dictionary comprehension,

dic = { k: [x for x in range(1,11) if x not in v] for k, v in d.items()}

Output:

{'1': [1, 4, 7, 8, 9, 10], '4': [2, 3, 4, 5, 7, 9, 10]}
Answered By: Always Sunny
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.