简体   繁体   English

显示嵌套字典的条目

[英]Display entries of nested dict

I have a nested dict that looks like this: 我有一个嵌套的字典,看起来像这样:

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

I want to be able to run a query that presents back the key 17733124060 and PhoneOwner Bob if the frequency is 0. 我希望能够运行一个查询,该查询在频率为0时显示键17733124060和PhoneOwner Bob。

So far I have: 到目前为止,我有:

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

But when I run this, I get an error: 但是当我运行它时,我得到一个错误:

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

What am I missing where? 我在哪里想念什么?

You could use a list comprehension to first build a list of matching entries and then print them as follows: 您可以使用列表推导来首先构建匹配条目的列表,然后按如下所示打印它们:

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

This would display the following: 这将显示以下内容:

17733124060 Bob
18444320742 Jane

Also, just in case, don't name your dictionary dict as this a builtin Python function. 另外,以防万一,不要将字典dict命名为内置Python函数。

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

You are trying to unpack two values ( dict.itertimes() returns 2-tuples) into 3 variables. 您试图将两个值( dict.itertimes()返回2元组)解压缩为3个变量。 Instead you should first iterate over the outer dict, then evaluate the nested dict: 相反,您应该首先遍历外部字典,然后评估嵌套字典:

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

Another approach could be using the built-in method, filter , where you filter your dictionary according to your condition ( sub_d[Frequency]==0 ), this way: 另一种方法可能是使用内置方法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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM