1

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
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
tslaw04
  • 21
  • 1
  • 3

4 Answers4

3

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]
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
2

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.

jepio
  • 2,276
  • 1
  • 11
  • 16
2

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
>>> 
GLHF
  • 3,835
  • 10
  • 38
  • 83
0
for k, v in bucket.iteritems():
    print k, v

a Joe  
c Scott  
b Brooke  
d Sam