简体   繁体   English

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

[英]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.

相关问题 如何根据其他键更新默认字典中的值 - How to update values in a defaultdict depending on other keys Python,如何根据其他列中的其他值替换值? - Python, How can I replace values depending on other values in other columns? 如何从字典中提取确切的键及其值? - How can I extract exact key and its values from a dictionary? 如何从具有{“ key”:[{“ A”:“ 1”},{“ B”:“ 2”}]]的字典中提取键? - How do I extract keys from a dictionary that has {“key”:[{“A”:“1”},{“B”:“2”}]? 如何根据其他键名对字典中的键(由数字组成)进行排序或更改? - How can I sort or change keys (consisting of numbers) in dictionary, based on other key names? 如何将 xml 节点和关键值提取到 R studio 中的 data.frame,包括 NA 值? - How can I extract xml nodes and key values to data.frame in R studio, including NA values? 如何从包含单个键的多个值的字典中提取值? - How can i extract values from a dictionary containing multiple values for a single key? 如何从两个列表创建字典,一个列表是键,另一个包含嵌套值? - How can I create a dictionary from two lists, one list is the keys, the other contains nested values? 如何创建嵌套字典键并从命名空间键值对列表中为其分配值? - how can I create nested dictionary keys and assign them values from a list of namespaced key value pairs? 如何将字典中的键更改为大写并在结果字典中添加相同键的值? - How can I change keys in a dictionary to upper case and add values of the same key in the resulting dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM