Kumar
Kumar

Reputation: 13

Convert unicode String to Dictionary in python

I have a variable which holds the table name and columns as a string. Below is the sample:

[(u'USER_SSO_PROPERTIES', u'[\n  "FULL_NAME",\n  "NAME"\n]'), (u'USERS', u'[\n  "EMAIL",\n  "NAME"\n]'), (u'PITCH_RECIPIENTS', u'[\n  "EMAIL",\n  "ID"\n]'), (u'USER_CLOUD_SERVICES', u'[\n  "EMAIL"\n]')]

I am trying to convert into a dictionary in python as below.

{'USER_SSO_PROPERTIES': ['FULL_NAME','NAME'],
 'PITCH_RECIPIENTS':['USER_CLOUD_SERVICES','EMAIL']}

How can I remove the \n and u and also convert it into the above format. I searched on SO and those solutions did not work for me.

Upvotes: 0

Views: 60

Answers (3)

Yaakov Bressler
Yaakov Bressler

Reputation: 12018

Simple 1 liner using eval:

my_data = {k:eval(v) for k,v in text}

Upvotes: 0

Jeongmin
Jeongmin

Reputation: 166

Use eval() to quickly convert literals to actual Python values.

This code can convert your example.

string = r'''[(u'USER_SSO_PROPERTIES', u'[\n  "FULL_NAME",\n  "NAME"\n]'), (u'USERS', u'[\n  "EMAIL",\n  "NAME"\n]'), (u'PITCH_RECIPIENTS', u'[\n  "EMAIL",\n  "ID"\n]'), (u'USER_CLOUD_SERVICES', u'[\n  "EMAIL"\n]')]'''

result_dict = {}
for table_name, columns_string in eval(string):
    result_dict[table_name] = eval(columns_string)

print(result_dict)

Try to run this code with other strings here.

https://www.pythonpad.co/pads/ri8adgokb5our8v1/

Upvotes: 1

Kevin Mayo
Kevin Mayo

Reputation: 1159

You could use ast.literal_eval and list-comprehension to achieve that:

import ast

t = [(u'USER_SSO_PROPERTIES', u'[\n  "FULL_NAME",\n  "NAME"\n]'), (u'USERS', u'[\n  "EMAIL",\n  "NAME"\n]'),
     (u'PITCH_RECIPIENTS', u'[\n  "EMAIL",\n  "ID"\n]'), (u'USER_CLOUD_SERVICES', u'[\n  "EMAIL"\n]')]
result = {k: ast.literal_eval(v) for k, v in t}
# {'USER_SSO_PROPERTIES': ['FULL_NAME', 'NAME'], 'USERS': ['EMAIL', 'NAME'], 'PITCH_RECIPIENTS': ['EMAIL', 'ID'], 'USER_CLOUD_SERVICES': ['EMAIL']}

Upvotes: 0

Related Questions