Say I have a list holding the following items:

``["FOO x 2", "BAR x 11", "PERC"]``

I would like to convert this list to a dictionary with the following result:

``{"FOO": 2, "BAR": 11, "PERC": 1}``

Any ideas on how to approach this problem?

You could go with supplying a comprehension to `dict`:

``````l = ["FOO x 2", "BAR x 11", "PERC"]
d = dict((tuple(map(str.strip, i.split('x'))) if 'x' in i else (i, 1) for i in l))
print(d)
{'BAR': '11', 'FOO': '2', 'PERC': 1}
``````

Though a `for-loop` definitely beats it in readability:

``````d = {}
for i in l:
if 'x' in i:
k, v = map(str.strip, i.split('x'))
d[k] = v
else:
d[i] = 1
``````

Below snippet code can do what you want to do

``````lst = ["FOO x 2", "BAR x 11", "PERC"];
lst1 = list()
for elem in lst:
splited = elem.split('x')
k = 0
for stri in splited:
k = k + 1
if k == 1:
v = stri
u = 1
else:
u = stri
ar = list()
ar.append(v)
ar.append(u)
lst1.append(ar)
dic = dict(lst1)
print(dic)
``````

A one-liner:

``````d = {x[0].strip(): int(x[1]) for x in ((elm + 'x 1').split('x') for elm in lst)}

print(d)
``````

Output:

``````{'BAR': 11, 'FOO': 2, 'PERC': 1}
``````

Alternatively, you can take advantage of the new unpacking feature with `*` in Python 3:

``````lst =  ["FOO x 2", "BAR x 11", "PERC"]

res = {}
for x in lst:
name, *count = (x + 'x 1').split('x')
res[name.strip()] = int(count[0])

print(res)
``````

Output: {'BAR': 11, 'FOO': 2, 'PERC': 1}

One more contrib to the zoo: now with list comprehension, splitting, and `if` expression:

``````pass1 = [x.split(' x ') for x in l]
# [['FOO', '2'], ['BAR', '11'], ['PERC']]
dict((t[0], int(t[1]) if len(t) > 1 else 1) for t in pass1)
# {'PERC': 1, 'BAR': 11, 'FOO': 2}
``````

Couple of options to choose from

``````data = ["FOO x 2", "BAR x 11", "PERC"]
``````

``````res = { key : int(value) if value else 1
for key, sep, value in map(lambda s: s.partition(' x '), data) }
``````

``````res = {}
for item in data:
key, sep, value = item.partition(' x ')
res[key] = int(value) if value else 1
``````

``````res = {}
for item in data:
key, *value = item.split(' x ')
res[key] = int(value[0]) if value else 1
``````

``````res = {}
for item in data:
key, value = (item.split(' x ') + [1])[:2]
res[key] = int(value)

# Output - res
{'FOO': 2, 'BAR': 11, 'PERC': 1}
``````

Note that this is assuming that your data will always be in that format, otherwise may need to include `.strip()` or other minor changes.

Top