如何根据其他键

时间:2017-03-13 04:31:07

标签: python dictionary

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

[{
   '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'。理想情况下,这将是一个新的字典列表,平均出生年份,取决于家庭:

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

我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用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}]
相关问题