TAGS :Viewed: 10 - Published at: a few seconds ago

[ Need more than 0 values to unpack ]

I have some code:

text = ''
for key, value in d:
    text += k + ' ' + str(v) + '\n'
file = open('ATM Data', 'w')

and when it runs it raises a

ValueError: need more than 0 values to unpack

but actually I do have some things in my dictionary. Can anyone help?

Answer 1

If d is dictionary then you have to use d.items() or d.iteritems() to get key, value as pair.

Answer 2

The iterator of a dictionary only iterates over the keys, thus either you can use the items (portable), or just iterate over the key and fetch the values:

for key, value in d.items():
    text += key + ' ' + str(value) + '\n'


for key in d:
    text += key + ' ' + str(d[key]) + '\n'

Notice that you can get much more performance by using join with generator expression however:

text = '\n'.join('{} {}'.format(key, value) for key, value in d.items()) + '\n'