0

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.

2
  • which version of python are you using? Commented Jul 24, 2020 at 2:01
  • I am using python 3 Commented Jul 24, 2020 at 2:05

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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']}

Comments

0

Simple 1 liner using eval:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.