-3

how can i change the dict values which digit to int and have no quotes

User input this string

{"name":"John", "age":30, "city":"New York"}

what ive tried

t=[x for x in input()[2:-1].split(", ")]
w=[]
for i in t:
    a=i
    e=a.replace("'","").replace('"','').split(":")
    w.append(e)
for i in w:
    for j in i:
        if j.isdigit():
            j=int(j)
d=[tuple(x) for x in w]
print(d)

It shows that 30 type int but it has quotes

Output

[('name', 'John'), ('age', '30'), ('city', 'New York')]

I want 30 to be without quotes

[('name', 'John'), ('age', 30), ('city', 'New York')]
Aha
  • 15
  • 5

2 Answers2

1

Given this string

string = '{"name":"John", "age":30, "city":"New York"}'

Parse it to a dict with

import ast
data = ast.literal_eval(string)

then get its items

print(list(data.items()))

[('name', 'John'), ('age', 30), ('city', 'New York')]
khelwood
  • 52,115
  • 13
  • 74
  • 94
  • isnt there basic ways without all this import staff and libr? – Aha Jan 22 '22 at 12:14
  • It doesn't get any more basic than this. `ast` is module from Pythons standard library and if it provides you with a simple solution you should use it and not try to invent the wheel yourself. – Matthias Jan 22 '22 at 13:01
1

This is JSON

import json

spam = '{"name":"John", "age":30, "city":"New York"}'
eggs = json.loads(spam)
print(eggs)
print(eggs['age'])

output:

{'name': 'John', 'age': 30, 'city': 'New York'}
30
buran
  • 11,840
  • 7
  • 28
  • 49
  • i kinda know that with json but in this case Its USER INPUT {"name":"John", "age":30, "city":"New York"} – Aha Jan 22 '22 at 12:15
  • So, store the user input in a variable and use it. What is the problem? I just hard-code the user input for the code example. – buran Jan 22 '22 at 12:16
  • i think u right but i just want to be able to do it without some imports – Aha Jan 22 '22 at 12:19