1

I am trying to loop 2 lots of 'key, value' so I can print 2 lots of data on the same line. However it seems my code prints the output I need, but it is repeating 4 times whereas I need it to only print once. My piece of code:

    for key1, value1 in dict1.items():
        pct = value1 * 100.0 / s // 1
        for key2, value2 in dict2.items():
            pct2 = value2 * 20
            print(key1, ":", int(pct), "% vs", pct2, "%")

Output:

A : 55 % vs 60 %
A : 55 % vs 20 %
A : 55 % vs 0 %
A : 55 % vs 20 %
B : 25 % vs 60 %
B : 25 % vs 20 %
B : 25 % vs 0 %
B : 25 % vs 20 %
C : 0 % vs 60 %
C : 0 % vs 20 %
C : 0 % vs 0 %
C : 0 % vs 20 %
D : 17 % vs 60 %
D : 17 % vs 20 %
D : 17 % vs 0 %
D : 17 % vs 20 %

But the output I'm needing is:

A : 55 % vs 60 %
B : 25 % vs 20 %
C : 0 % vs 0 %
D : 17 % vs 20 %

I have tried many ways around this, but I cant seem to figure a way to print the output I need.

4 Answers 4

1
for k in dict1: 
    print("{} : {}% vs {}%".format(k, int(dict1[k]*100.0 / s), dict2[k]*20))
Sign up to request clarification or add additional context in comments.

Comments

1

For Python 3.6+, I'd recommend

for k, v in dict1.items(): 
    print(f'{k} : {v * 100.0 / s}% vs {dict2[k] * 20}%')

Otherwise, I'd suggest

for k, v in dict1.items(): 
    print('{} : {}% vs {}%'.format(k, int(v * 100 / s), dict2[k] * 20))

This also enforces the implicit precondition of dict2 having keys that are a weak superset of dict1's keys (i.e. dict2 has all of the keys that dict1 has and maybe more.

Comments

0

Probably not the best solution but I hope that it will work

tmpValueForKey1 = 1
tmpValueForKey2 = 1
for key1, value1 in dict1.items():
    pct = value1 * 100.0 / s // 1
    for key2, value2 in dict2.items():
        pct2 = value2 * 20
        if tmpValueForKey1 == tmpValueForKey2:
            print(key1, ":", int(pct), "% vs", pct2, "%")
        tmpValueForKey2 = tmpValueForKey2 + 1
    tmpValueForKey1 = tmpValueForKey1 + 1

Comments

-1

You can use the zip() function to create an Iterable. Then, you can loop over the values like this:

for keys in zip(dict1, dict2):

  # Get Keys
  key1 = keys[0]
  key2 = keys[1]

  # Get Values
  pct1 = dict1[key1]
  pct2 = dict2[key2]
  print(key1, ":", int(pct1), "% vs", pct2, "%")

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.