如何根据其他键提取键的值

2024-04-19 20:00:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的字典列表:

[{
   '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'
 }...]

我想做的是根据“家”键找到“出生”的平均值。理想情况下,这将是一个新的字典列表,根据家庭的不同,列出平均出生年份:

[{
  'home': 'San Francisco',
  'birth': (average of the birth year, of everyone in the list with the key 'home'
    and value 'San Francisco')
}, ....]

我该怎么做?你知道吗


Tags: ofthenamehome列表字典jobjohn
1条回答
网友
1楼 · 发布于 2024-04-19 20:00:20

使用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()]

输出

[{'home': 'San Francisco', 'birth': 1987}, {'home': 'Chicago', 'birth': 1972}, {'home': 'LA', 'birth': 1983}]

相关问题 更多 >