Reputation: 854
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.
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?
Upvotes: 0
Views: 47
Reputation: 10961
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:
>>> 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
Upvotes: 0
Reputation: 1309
for phoneNumber, PhoneOwner, Frequency in dict.iteritems():
You are trying to unpack two values (dict.itertimes()
returns 2-tuples) into 3 variables. 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']
Upvotes: 1
Reputation: 46789
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.
Upvotes: 1