1

I have this kind of dictionary in python:

x = {'test': {1: 2, 2: 4, 3: 5},
     'this': {1: 2, 2: 3, 7: 6},
     'is': {1: 2},
     'something': {90: 2,92:3}}

I want to modify all of the value in the key by whatever value I want. Let's say 100, the methods I tried are below:

counter = 1
print(x)
for key,anotherKey in x.items():
    while counter not in x[key]:
        counter+=1
    while counter in x[key]:
        x[key][counter] = 100
        counter+=1
    counter =0

Which got the result below:

{'test': {1: 100, 2: 100, 3: 100},
 'this': {1: 100, 2: 100, 7: 6},
 'is': {1: 100},
 'something': {90: 100,92: 3}}

I know why this is happening it's because the loop doesn't consider if the differences is more than 1 which in this case in 'this' : where the differences from 2 to 7 is more than 1. However I don't know how to solve this.

2
  • 6
    What is your desired output? Commented May 9, 2018 at 15:39
  • Did one of the 2 solutions below help? Feel free to accept one if it did (green tick on left), or ask for clarification. Commented May 11, 2018 at 13:09

2 Answers 2

4

You can iterate via a nested for loop:

x = {'test': {1: 2, 2: 4, 3: 5},
     'this': {1: 2, 2: 3, 7: 6},
     'is': {1: 2},
     'something': {90: 2,92:3}}

for a in x:
    for b in x[a]:
         x[a][b] = 100

print(x)

{'is': {1: 100},
 'something': {90: 100, 92: 100},
 'test': {1: 100, 2: 100, 3: 100},
 'this': {1: 100, 2: 100, 7: 100}}

Or for a new dictionary you can use a dictionary comprehension:

res = {a: {b: 100 for b in x[a]} for a in x}
Sign up to request clarification or add additional context in comments.

Comments

-1

You can use dictionary comprehension in this way:

{a: {b:100 for b in d} for (a,d) in x.items()}

Comments

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.