1

I have a JSON file of the following format:

[
    {"url": "example1.com", "date": "Jan 1", "text": "Example text 1"},
    {"url": "example2.com", "date": "Jan 2", "text": "Example text 2"}
]

Which I upload into Python using:

with open("data.json") as data:
    data = json.load(data)

I would like to reformat the uploaded data to the following format:

[
   ("Example text 1", {"url": "example1.com", "date": "Jan 1"}),
   ("Example text 2", {"url": "example2.com", "date": "Jan 2"})
]

1 Answer 1

2

We can use dict.pop for each dictionary to create the tuples in a loop:

data = [
{"url": "example1.com", "date": "Jan 1", "text": "Example text 1"},
{"url": "example2.com", "date": "Jan 2", "text": "Example text 2"}
]

# make tuples
[(d.pop('text'), d) for d in data]

# [('Example text 1', {'url': 'example1.com', 'date': 'Jan 1'}),
#  ('Example text 2', {'url': 'example2.com', 'date': 'Jan 2'})]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.