Home > Blockchain >  Organizing a list of dictionaries in Python
Organizing a list of dictionaries in Python

Time:08-25

I have a huge list of dictionaries with data labeled as follows

{'id': 2,
 'text': '"The hotel has many restaurants to enjoy a meal. My husband and I went to the Japanese restaurant and we only found sushi. Considering that it is an international hotel, they should have a larger variety of options.',
 'label': [[0, 46, 'general services'], [47, 214, 'japanese food']]},

And I want to create a new key called annotations that indicates the start and end for the whole list of dictionaries. For this one I did the following process

review2 = data[2]
review2['content'] = review2['text']
review2['annotations'] = list()
for l in review2['label']:
  d = {'start': l[0],'end': l[1],'label': l[2]}
  review2['annotations'].append(d)

And then I got

{'id': 2, 'content': 'The hotel has many restaurants to enjoy a meal. My husband and I went to the Japanese restaurant and we only found sushi. Considering that it is an international hotel, they should have a larger variety of options', 'annotations': [{'start': 0, 'end': 46, 'label': 'general services'}, {'start': 47, 'end': 214, 'label': 'japanese food'}]}

So I want to do this process over a bigger list of dictionaries. I really appreciate your help.

CodePudding user response:

You can use zip and dict to make it more simpler.
And using map to iterate over the whole list.

x = {"id": 2, "text": "data", "label": [[0, 46, "general services"], [47, 214, "japanese food"]]}
dict_keys = ["start", "end", "label"]
x["annotations"] = list(map(lambda list_item: dict(zip(dict_keys, list_item)), x["label"]))

Edit

PLEASE read my example code clearfully again and try to understand the logic behind the code. Do not just paste it in your code.

review2 = data[2]
review2['content'] = review2['text']
dict_keys = ["start", "end", "label"]
review2['annotations'] = list(map(lambda list_item: dict(zip(dict_keys, list_item)), review2["label"]))

CodePudding user response:

You can get all the operations you want to do to transform each data record, and pack it into a function.

def transform(*, id, text, label):
  annotations = [dict(start=s, end=e, label=l) for s, e, l in label]
  return dict(id=id, content=text, annotations=annotations)

When you have the transform operation defined, you can map this function to all elements of the list.

reviews = list(transform(**d) for d in data)
  • Related