Home > other >  Convert value of dictionary to dictionary Python
Convert value of dictionary to dictionary Python

Time:09-28

How I can convert the value of my key to another dictionary?

dic1 = {'data': 'key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47'}

End result:

result = {'IAfpK': 58,
          'WNVdi': 64,
          'jp9zt': 47
}

CodePudding user response:

If the data key has always the same format, you can do:

dic1 = {"data": "key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}

s = dic1["data"].split(",")

out = {}
for key, age in zip(s[::2], s[1::2]):
    key = key.split("=")[-1].strip()
    age = age.split("=")[-1].strip()
    out[key] = int(age)

print(out)

Prints:

{'IAfpK': 58, 'WNVdi': 64, 'jp9zt': 47}
  • Related