[英]List comprehension on a list of dictionaries
我有一个这样的字典列表:
[{'end': 34,
'entity_group': 'ORG',
'score': 0.99919325,
'start': 0,
'word': ' Community College Alabama'},
{'end': 54,
'entity_group': 'LOC',
'score': 0.90115756,
'start': 42,
'word': ' Maxwell Blvd'},
{'end': 66,
'entity_group': 'LOC',
'score': 0.9890175,
'start': 56,
'word': ' Montgomery'},
{'end': 70,
'entity_group': 'LOC',
'score': 0.9988833,
'start': 68,
'word': ' AL'}]
我想提取word
的值,但只提取'entity_group': 'LOC'
值。 所以对于上面的例子,那将是:
[' Maxwell Blvd', ' Montgomery', ' AL']
我试过这样做:
[[item for item in d.items()] for d in a]
...但这不会产生我想要的。
如果您的字典中不存在entity_group
密钥,我会选择get
以确保安全。 如果您使用括号访问该不存在的密钥,您将得到一个KeyError
。
data = [{'end': 34,
'entity_group': 'ORG',
'score': 0.99919325,
'start': 0,
'word': ' Community College Alabama'},
{'end': 54,
'entity_group': 'LOC',
'score': 0.90115756,
'start': 42,
'word': ' Maxwell Blvd'},
{'end': 66,
'entity_group': 'LOC',
'score': 0.9890175,
'start': 56,
'word': ' Montgomery'},
{'end': 70,
'entity_group': 'LOC',
'score': 0.9988833,
'start': 68,
'word': ' AL'}]
words_for_loc_group = [item.get('word') for item in data if item.get('entity_group') == 'LOC']
我认为这对你有用。
data = [
{'entity_group': 'ORG', 'score': 0.99919325, 'word': ' Community College Alabama', 'start': 0, 'end': 34},
{'entity_group': 'LOC', 'score': 0.90115756, 'word': ' Maxwell Blvd', 'start': 42, 'end': 54},
{'entity_group': 'LOC', 'score': 0.9890175, 'word': ' Montgomery', 'start': 56, 'end': 66},
{'entity_group': 'LOC', 'score': 0.9988833, 'word': ' AL', 'start': 68, 'end': 70}]
res = [i.get("word") for i in data if i.get("entity_group") == "LOC"]
[d['word'] for d in a if d['entity_group'] == 'LOC']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.