Home > Blockchain >  Python: Get all values from like keys in list of dictionaries
Python: Get all values from like keys in list of dictionaries

Time:08-13

I have a list of dictionaries:

original_data = [{"id":1, "other_fields":"other_data"},{"id":2, "other_fields":"other_data"},{"id":3, "other_fields":"other_data"}]

I need to be able to do get the values of all of the "id" keys and add them into a new list of dictionaries:

new_data = [{"id":1, "processed_data":"processed data"}]

Adding to or replacing anything in the original list of dictionaries is not an option. It will be working with a rather large list.

CodePudding user response:

You can try below to filter for what is needed

original_data = [{"id":1, "other_fields":"other_data1"},{"id":2, "other_fields":"other_data2"},{"id":3, "other_fields":"other_data3"}]
df = pd.DataFrame(original_data)
print(df)

   id other_fields
0   1  other_data1
1   2  other_data2
2   3  other_data3

The keys are

list(df['id'])

[1, 2, 3]

The values are

list(df['other_fields'])

['other_data1', 'other_data2', 'other_data3']

CodePudding user response:

For loop:

new_data = []

for data in original_data:
    new_data.append({"id": data["id"], "processed_data": "processed_data"})

One-liner:

new_data = [{"id": data["id"], "processed_data": "processed_data"} for data in original_data]
  • Related