显示嵌套字典

时间:2015-12-09 15:58:47

标签: python dictionary nested

我有一个嵌套的dict,如下所示:

17733124060: {'PhoneOwner': u'Bob', 'Frequency': 0}, 
18444320737: {'PhoneOwner': u'Sarah', 'Frequency': 1}, 
18444320742: {'PhoneOwner': u'Jane', 'Frequency': 0}

如果频率为0,我希望能够运行一个显示密钥17733124060和PhoneOwner Bob的查询。

到目前为止,我有:

for phoneNumber, PhoneOwner, Frequency in dict.iteritems():
    if Frequency == 0:
    print phoneNumber + PhoneOwner

但是当我运行它时,我收到一个错误:

for phoneNumber, PhoneOwner, Frequency in phoneNumberDictionary.iteritems():
ValueError: need more than 2 values to unpack

我在哪里错过了什么?

3 个答案:

答案 0 :(得分:1)

您可以使用列表推导来首先构建匹配条目列表,然后按如下方式打印它们:

my_dict = {
    17733124060: {'PhoneOwner': u'Bob', 'Frequency': 0}, 
    18444320737: {'PhoneOwner': u'Sarah', 'Frequency': 1}, 
    18444320742: {'PhoneOwner': u'Jane', 'Frequency': 0}}

zero_freq = [(k, v['PhoneOwner']) for k, v in my_dict.items() if v['Frequency'] == 0]

for number, owner in zero_freq:
    print number, owner

这将显示以下内容:

17733124060 Bob
18444320742 Jane

另外,为了以防万一,请不要将您的字典dict命名为内置Python函数。

答案 1 :(得分:1)

  

for phoneNumber, PhoneOwner, Frequency in dict.iteritems():

您正在尝试将两个值(dict.itertimes()返回2元组)解压缩为3个变量。相反,你应首先迭代外部字典,然后评估嵌套字典:

for phoneNumber, inner_dict in phonenumbers.iteritems():
    if inner_dict['Frequency'] == 0:
        print str(phoneNumber) + inner_dict['PhoneOwner']

答案 2 :(得分:0)

另一种方法可能是使用内置方法filter,您可以根据条件(sub_d[Frequency]==0)过滤字典,这样:

>>> d
{17733124060L: {'Frequency': 0, 'PhoneOwner': u'Bob'}, 18444320742L: {'Frequency': 0, 'PhoneOwner': u'Jane'}, 18444320737L: {'Frequency': 1, 'PhoneOwner': u'Sarah'}}
>>> for i in filter(lambda s:d[s]['Frequency']==0, d):
    print '%d %s' % (i, d[i]['PhoneOwner'])


17733124060 Bob
18444320742 Jane