Home > OS >  how to use the dict() with only one variable?
how to use the dict() with only one variable?

Time:12-31

I have a variable called "dict_str" that looks like this : "a = 15, a2 = 19" (it continue for thousands of inputs). If I try to use the dict function :

dict(dict_str) 

it gives me this error :

ValueError: dictionary update sequence element #0 has length 1; 2 is required

But if I do this :

 dict(a = 15, a2 = 19)

it works fine. So I am wondering if their's a way to make it works with the dict_str variable

CodePudding user response:

This is a work around.

items = [item.split('=') for item in dict_str.split(', ')]

my_dict = {}
for key, value in items:
    my_dict[key.strip()] = int(value.strip())

print(my_dict)

Output:

{'a': 15, 'a2': 19}

You could even use regex if you wish.

Example:

import re

regex = re.compile(r'(\w ) *= *(\d )') 
items = regex.findall(dict_str)
my_dict = {key: int(value) for key, value in items) 

print(my_dict) 

This regex should produce same output.

CodePudding user response:

One liner:

dmap = dict(map(str.strip, array.split("=")) for array in "a = 15, a2 = 19".split(","))

Decompressing it:

data = "a = 15, a2 = 19" 

dmap = dict(map(str.strip, array.split("=")) for array in data.split(","))

print(dmap)

Better approach:

data = "a = 15, a2 = 19"

dmap = {}

for value in data.split(","):
    array = value.split("=")
    dmap[array[0].strip()] = int(array[1].strip())
  • Related