Can someone please tell me why I am getting an unpacking error in the below code?
bucket = {
'a': 'Joe',
'b': 'Brooke',
'c': 'Scott',
'd': 'Sam',
}
for i, kv in enumerate(bucket):
k, v = kv
print i, k, v
Can someone please tell me why I am getting an unpacking error in the below code?
bucket = {
'a': 'Joe',
'b': 'Brooke',
'c': 'Scott',
'd': 'Sam',
}
for i, kv in enumerate(bucket):
k, v = kv
print i, k, v
Because kv
isn't something that can be unpacked: its one of the keys to your dictionary. Maybe what you meant is:
for i, k in enumerate(bucket):
print i, k, bucket[k]
Iterating over a dict returns only the keys, if you want key value pairs you have to use dict.items()
:
for i, kv in enumerate(bucket.items()):
k, v = kv
print i, k, v
Or even better, unpack directly in the loop:
for i, (k, v) in enumerate(bucket.items()):
print i, k, v
Also notice that the items will not be ordered by key. If you want them ordered, use either collections.OrderedDict
or sorted()
with a key function.
It's not a correct way, you thought you can break into pieces like key-valuebut kv
equals to your dict keys . It's not like that. kv
is a variable that takes your dict keys.
bucket = {
'a': 'Joe',
'b': 'Brooke',
'c': 'Scott',
'd': 'Sam',
}
for i, kv in enumerate(bucket):
print (i,kv)
>>>
0 a
1 c
2 b
3 d
>>>
You see, only keys here. The solution is;
bucket = {
'a': 'Joe',
'b': 'Brooke',
'c': 'Scott',
'd': 'Sam',
}
for i, kv in enumerate(bucket):
print (i,kv,bucket[kv])
>>>
0 c Scott
1 a Joe
2 d Sam
3 b Brooke
>>>
for k, v in bucket.iteritems():
print k, v
a Joe
c Scott
b Brooke
d Sam