Shankar
Shankar

Reputation: 3624

Python try except continue fails to print expected results

Can someone point out where am I going wrong, What is actually happening here exactly with except continue or a better way to tackle this problem.

dic = {'arun': 123213, 'hari': 31212, 'akila': 321, 'varun': 12132, 'apple': 3212}
u1 = {'arun': 123123, 'orange': 1324214}
u2 = {'akila': 1234124, 'apple': 123123}
u3 = {'hari': 144}
u4 = {'anna': 23322}
for key, value in dic.iteritems():
    try:
        A = u1[key]
        B = u2[key]
        C = u3[key]
        D = u4[key]

    except KeyError:
        continue
    print A, B, C, D  # fails to print 

Upvotes: 0

Views: 236

Answers (4)

hughdbrown
hughdbrown

Reputation: 49013

Try this:

dic = {'arun': 123213, 'hari': 31212, 'akila': 321, 'varun': 12132, 'apple': 3212}
u1 = {'arun': 123123, 'orange': 1324214}
u2 = {'akila': 1234124, 'apple': 123123}
u3 = {'hari': 144}
u4 = {'anna': 23322}

for key in dic:
    print list(d.get(key) for d in (u1, u2, u3, u4))

It prints your output as a list:

>>> for key in dic:
...     print list(d.get(key) for d in (u1, u2, u3, u4))
... 
[123123, None, None, None]
[None, 1234124, None, None]
[None, 123123, None, None]
[None, None, 144, None]
[None, None, None, None]

Upvotes: 0

Stephane Rolland
Stephane Rolland

Reputation: 39906

  • u2['hari'] will raise an exception
  • u3['akila'] will also raise an exception
  • u4['varun'] will again also raise an exception

you are trying each time to use a item from a dictionary although the item doesn't exists

Upvotes: 0

FoxMulder900
FoxMulder900

Reputation: 1291

Your 'uX' dictionaries do not have the same keys as 'dic' so it is failing when trying to retrieve those values. Then you are catching the exception and calling 'continue' which automatically jumps back to the top of your loop before your print statement executes.

Try taking out the try/except statement and the Python interpreter will spit out an error of exactly where your problem is.

Upvotes: 0

ecatmur
ecatmur

Reputation: 157344

The continue will skip to the next key from dic if any lookup fails. You want to use an operation which is guaranteed to give a result even if the key is not found, e.g. dict.get:

for key, value in dic.iteritems():
    A = u1.get(key)  # A is None if not found
    # ...
    print A, B, C, D

Upvotes: 6

Related Questions