Turn String Input into Hash Python

Решая задания на Codewars наткнулся на такую задачу:

Please write a function that will take a string as input and return a hash. The string will be formatted as such. The key will always be a symbol and the value will always be an integer.
"a=1, b=2, c=3, d=4"
This string should return a hash that looks like
{ 'a': 1, 'b': 2, 'c': 3, 'd': 4}

Мое решение этой задачи:

def str_to_hash(s): 
    s.split(', ')
    s = dict([tuple(i.split('=')) for i in s])
    s = {k:int(v) for k,v in s.items()}
    return s

Выводит ошибку:

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

Подскажите, что я делаю не так?


Ответы (2 шт):

Автор решения: MBo

Результат сплита никуда не записывается.
И не экономьте переменные...

def str_to_hash(s):
    q = s.split(', ')
    t = dict([tuple(i.split('=')) for i in q])
    u = {k:int(v) for k,v in t.items()}
    return u
→ Ссылка
Автор решения: SergFSM

входные данные уже содержат почти готовый конструктор словаря, поэтому в принципе можно это использовать и сделать так:

def str_to_hash(s): 
    return eval(f'dict({s})')

str_to_hash("a=1, b=2, c=3, d=4")  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
→ Ссылка