[英]How can I extract values of a key depending on other keys
I have a list of dictionaries like this: 我有这样的词典列表:
[{
'name': 'John',
'birth': '1988',
'job': 'accountant',
'home': 'San Francisco'
}, {
'name': 'Kelly',
'birth': '1983',
'job': 'lawyer',
'home': 'LA'
}, {
'name': 'Bob',
'birth': '1972',
'job': 'driver',
'home': 'Chicago'
}, {
'name': 'Betty',
'birth': '1986',
'job': 'teacher',
'home': 'San Francisco'
}...]
What I want to do is to find the average of 'birth' depending on the key 'home'. 我想要做的是根据关键“家庭”来找到“出生”的平均值。 Ideally this will be a new list of dictionaries with average of birth year, depending on home:
理想情况下,这将是一个平均出生年份的新字典列表,具体取决于家庭:
[{
'home': 'San Francisco',
'birth': (average of the birth year, of everyone in the list with the key 'home'
and value 'San Francisco')
}, ....]
How can I do this? 我怎样才能做到这一点?
Use defaultdict
to group homes and then take average of birth 使用
defaultdict
对房屋进行分组,然后平均出生
from collections import defaultdict
births = defaultdict(list)
records = [{'home': 'San Francisco', 'job': 'accountant', 'name': 'John', 'birth': '1988'}, {'home': 'LA', 'job': 'lawyer', 'name': 'Kelly', 'birth': '1983'}, {'home': 'Chicago', 'job': 'driver', 'name': 'Bob', 'birth': '1972'}, {'home': 'San Francisco', 'job': 'teacher', 'name': 'Betty', 'birth': '1986'}]
for record in records:
births[record['home']].append(int(record['birth']))
print [{'home':k,'birth':sum(v)/len(v)} for k,v in births.iteritems()]
Output 输出量
[{'home': 'San Francisco', 'birth': 1987}, {'home': 'Chicago', 'birth': 1972}, {'home': 'LA', 'birth': 1983}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.