V
V
Vladislav Shepilov2014-02-07 16:59:07
Python
Vladislav Shepilov, 2014-02-07 16:59:07

How to create a Python dictionary?

I have data:

data = """
rules:      evdev
model:      pc105
layout:     us,ru
variant:    ,
options:    grp:alt_shift_toggle,grp_led:scroll
"""

I want to get a dictionary
{'layout': 'us,ru',
'model': 'pc105',
'options': 'grp:alt_shift_toggle,grp_led:scroll',
'rules': 'evdev',
'variant': ', '}
I do this:
dict((a, b.strip()) for a, b in
                 (item.split(":") for item in
                  data.splitlines()))

I get:
dict((a, b.strip()) for a, b in
ValueError: too many values ​​to
unpack

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
theaidem, 2014-02-07
@kripton3000

Maybe it's a bunch of colons "options: grp: alt_shift_toggle, grp_led: scroll"
Although here:

d = {}
for x in data.splitlines():
    x = x.split(': ')
    if x[0]: d[x[0]] = x[1]
print d

Sooo messy but it works!

A
Andrey Dugin, 2014-03-21
@adugin

As for the error, you forgot one closing parenthesis:
dict((a, b.strip()) <-- add a parenthesis here
, which doesn't help, because the syntax is wrong :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question