1

I have a variable called data. It contains following JSON value.

data=['{"time":["1000","MS"],"What is your name?":["John"]}']

I want to separate keys and values from it and want output like following.

Keys
-----
time 
What is your name?

Value:
------
1000 
MS
John

How to do it in python?

2 Answers 2

3

You can use json.loads to parse a json string

>>> data=['{"time":["1000","MS"],"What is your name?":["John"]}']
>>> a_dict = json.loads(data[0])

>>> a_dict.keys()
[u'What is your name?', u'time']
>>> a_dict.values()
[[u'John'], [u'1000', u'MS']]

Now you can use a simple for loop to print the output you required.

Or like

>>> print '\n'.join(a_dict.keys())
What is your name?
time
>>> print '\n'.join( '\n'.join(x )for x in a_dict.values() )
John
1000
MS
Sign up to request clarification or add additional context in comments.

3 Comments

How to separate multiple keys and values? I need output in the way I showed it in my question.
@user2151087 Aren't they separated already, the first is list of keys and the next list is of values. You cannot be sure of the order in which they occur because dictionaries are unordered list
@user2151087 Do take a look at the print statements, I think you are specifically looking for them
0

You can also use ast module :

>>> import ast
>>> ast.literal_eval(data[0])
{'What is your name?': ['John'], 'time': ['1000', 'MS']}
>>> d=ast.literal_eval(data[0])
>>> print '\n'.join(d.keys())
What is your name?
time
>>> print '\n'.join([j for i in d.values() for j in i])
John
1000
MS

2 Comments

How to separate multiple keys and values? I need output in the way I showed it in my question.
@user2151087 You can join them, with a newline character! and about the values since they are nested lists you can unpack them with a nested list comprehension!

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.