0

有人可以指出我哪里出错了,这里到底发生了什么,除了继续或解决这个问题的更好方法。

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 
4

4 回答 4

6

如果任何查找失败,continue它将跳到下一个键。dic您想使用即使找不到密钥也能保证给出结果的操作,例如dict.get

for key, value in dic.iteritems():
    A = u1.get(key)  # A is None if not found
    # ...
    print A, B, C, D
于 2013-04-19T19:40:26.403 回答
0

您的 'uX' 字典没有与 'dic' 相同的键,因此在尝试检索这些值时会失败。然后,您将捕获异常并调用“继续”,它会在您的打印语句执行之前自动跳回循环的顶部。

尝试取出 try/except 语句,Python 解释器会吐出一个错误,说明问题出在哪里。

于 2013-04-19T19:40:51.063 回答
0
  • u2['hari']将引发异常
  • u3['akila']也会引发异常
  • u4['varun']也会再次引发异常

您每次都尝试使用字典中的项目,尽管该项目不存在

于 2013-04-19T19:40:52.403 回答
0

试试这个:

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))

它将您的输出打印为列表:

>>> 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]
于 2013-04-19T21:14:09.597 回答