0

hi guyz,
i'm a Python user (not so long) , anyway i've read some stuff about lua .

i've written function like this

def pair(dic = {} ):
    return dic.keys(), dic.values()

a dictionary is a parameter to the pair function .
to use it like this :

dic = {1 : "Slackware", 2 : "Windows XP SP2"}
>>> for x, y in pair(dic):
    print x, y

anyway , it works fine with the dic but doesn't work with a dictionary like this :

dic2 ={"Operating System" : "Version", "Slackware": "11", "Ms Windows": "XP SP2"}

it produce this error : ValueError: too many values to unpack

i tried to use x, y in dic2.keys(), dic2.values() , and it still the same problem .
what do you think ?

3
Contributors
5
Replies
6
Views
9 Years
Discussion Span
Last Post by StrikerX
0

When I have these kinds of maddening bugs, I use print statements to see if my assumptions are correct. In this case, we are assuming that x and y will take on values of keys and values, respectively. But now:

>>> print pair(dic)
([1, 2], ['Slackware', 'Windows XP SP2'])
>>> print pair(dic2)
(['Ms Windows', 'Operating System', 'Slackware'], ['XP SP2', 'Version', '11'])

Note that pair() returns two lists: the list of keys and the list of values. So ...

>>> for item in pair(dic2):
    print item

['Ms Windows', 'Operating System', 'Slackware']
['XP SP2', 'Version', '11']

So what would the line

for x,y in pair(dic2) mean?

* Iterate through dic2
* Unpack each item, assumed to be a 2-sequence, and hand the first slot to x and the second slot to y.

Now the error message makes sense: each item in dic2 is a 3-sequence!

If you want to print key, value pairs, then this is much easier:

>>> def printdict(dic):
    for key in dic:
       print key,dic[key]
>>> printdict(dic)
1 Slackware
2 Windows XP SP2
>>> printdict(dic2)
Ms Windows XP SP2
Operating System Version
Slackware 11
>>>

(Although note that the dictionary comes out in non-deterministic order.)

Hope it helps,
Jeff

BTW -- anyone else notice that the "Toggle Plain Text" option seems to be broken recently?

0

I think our friend StrikerX might be looking for this ...

dic2 ={"Operating System" : "Version", "Slackware": "11", "Ms Windows": "XP SP2"}
 
for key, val in dic2.items():
    print key, val
0

Yes, vega's version does the same as mine.

what is broken in the "Toggle Plain Text" option?

Actually ... nothing now! (weird!!). From two days ago until right now, if I hit "Toggle Plain Text", it didn't do anything.

Hmm...

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.