0

I have dictionary which I'm looping through. I want to say that if a value == a certain number (0 in this case) then the value of the next iteration of the for loop will be 2x that value.

I have a dictionary like the following:

d = {'a' : 1, 'b' : 0, 'c' : 4}

When I loop through the dictionaries with a for loop I'd like to multiply the next iteration by 2 if the current iteration = 0.

for k, v in d.items():
    if k == 0:
        [next iteration v = v * 2]
    else:
        v = v + 1

So I would expect to end up with a dictionary like this:

d = {'a' : 2, 'b' : 0, 'c' : 9}

This is just a simple example but hopefully illustrates what I'm trying to achieve.

Thanks

2
  • 4
    The problem is, you are using dictionary and it doesn't keep its order so you'll most likely get different values for different runs. Commented Oct 13, 2016 at 12:51
  • Do you know of another way I could achieve this? Commented Oct 13, 2016 at 12:59

2 Answers 2

2

You can use orderedDict to have a dictionary and keep your order.

Looking at your algorithm, you are adding 1 to all values if it is not zero and if it is zero, you multiply the next item first, then add 1 to it. One of the basic and easiest way is, having a flag to decide if you should multiply the next value or not.

import collections

d = (("a", 1), ("b", 0), ("c", 4))
od = collections.OrderedDict(d)

multiply = False
for k in od.keys():
    if multiply:
        od[k] *= 2
    if od[k] != 0:
        od[k] += 1
        multiply = False
    else:
        multiply = True

print(od)
Sign up to request clarification or add additional context in comments.

Comments

0

Unfortunately you are using a dictionary, dictionaries do not keep there order. You would ave to use something such as a list. Not sure ho you would set key/value pairs in a list though.

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.