I know i can convert list of tuples to dict like that
list_of_tuples = [("k", 167), ("z", 179), ("u", 179), ("m", 267), ("a", 445), ("l", 134)]
new_dict = {}
new=dict{list_of_tuples}
print(new)
#{'k': 167, 'z': 179, 'u': 179, 'm': 267, 'a': 445, 'l': 134}
But what to do when i got user INPUTS this
[("k", 167), ("z", 179), ("u", 179), ("m", 267), ("a", 445), ("l", 134)]
as string
What User unputs in line as string
([("k", 167), ("z", 179), ("u", 179), ("m", 267), ("a", 445), ("l", 134)])
i tried with Json to convert to dict but couldn't because its list of tuples
CodePudding user response:
First, convert the string to a list and then you can do dictionary comprehension like this:
import ast
my_list = ast.literal_eval("[("k", 167), ("z", 179), ("u", 179), ("m", 267), ("a", 445), ("l", 134)]")
d = {k:v for k,v in my_list}
CodePudding user response:
Use a regular expression to replace (
, ,
inside tuple, and )
in the string with {
, :
and }
respectively.
>>> i = '[("k", 167), ("z", 179), ("u", 179), ("m", 267), ("a", 445), ("l", 134)]'
>>> j = re.sub(r'\(("\w"), (d )\)', r'{\1:\2}', i)
>>> d = json.loads(j)
>>> d
[{'k': 167}, {'z': 179}, {'u': 179}, {'m': 267}, {'a': 445}, {'l': 134}]