简体   繁体   English

迭代字典列表

[英]Iteration over a list of dictionaries

I'm trying to write a script that receives as input two lists of dictionaries, from two .csv files, checks for keys matches and gives another list of dictionaries with an output from the two lists. 我正在尝试编写一个脚本,该脚本从两个.csv文件接收两个字典列表作为输入,检查键匹配,并给出另一个字典列表以及两个列表的输出。 I have this so far: 到目前为止,我有:

import csv

def tabel_animals_func(file_csv):

 with open(ficheiro_csv, 'rU') as file_csv_animals:
    inputFile = csv.DictReader(file_csv_animals, delimiter=';')

    result_animals = []
    for line in inputFile:
        result_animals.append(line)
 return result_animals

def tabel_owners_func(file_csv2):

 with open(file_csv2, 'rU') as file_csv_owners:
    reader = csv.DictReader(file_csv_owners, delimiter=';')
    result_owners = []
    for line in reader:
        result_owners.append(line)
 return result_owners

def average_Age(tabela_animais, tabela_donos):

  var_owners = tabel_owners_func(tabel_owners)
  var_animals = tabel_animals_func(tabel_animals)

I need to make the third function output, a new list of dicts with the average age of the owners animals, the output is something like this: 我需要输出第三个函数,一个新的拥有所有者动物平均年龄的字典列表,输出是这样的:

  [{'Owners Name' : 'Jack', 'Average age' : '5'}, {'Owners Name' : 'Tom', 'Average age' : '8'}]

This is an input .csv file example, for the tabel_animals_func: 这是tabel_animals_func的输入.csv文件示例:

  Name of the animal;Species;Age
  Kiko;Cat;8
  Rocky;Turtle;57
  Snoopy;Dog;12
  Nemo;Fish;2
  Leonardo;Turtle;45
  Milo;Dog;9
  Raphael;Turtle;57
  Dory;Fish;4

tabel_owners_func input file: tabel_owners_func输入文件:

  Owners Name;Name of the animal
  Ana;Michelangelo
  Tom;Dory
  Jack;Kiko
  Tom;Snoopy
  Eva;Rocky
  Sara;Raphael
  Jack;Nemo

First, I'd like to suggest that you merge your two CSV reading functions. 首先,我建议您合并两个CSV读取功能。 If you take a step back, you'll see that those functions really just do the same thing. 如果退后一步,您会发现这些功能实际上只是在做同样的事情。 Combine them into a read_csv_contents function, or something. 将它们组合成read_csv_contents函数或其他内容。

You should probably convert the list-of-dicts returned by your animals reader into a dict-of-dicts with the animal name as the key: 您可能应该将动物阅读器返回的字典列表转换为以动物名称为键的字典:

var_animals = tabel_animals_func(tabel_animals)
animals = {data['Name of animal']:data for data in var_animals}

Once you have that, you can find the list of animals owned by each owner: 一旦有了它们,就可以找到每个所有者拥有的动物列表:

pets = {}
for owner in var_owners:
    o_name = owner['Owners Name']

    if o_name not in pets:
        pets[o_name] = []

    pets[o_name].append(animals['Name of animal'])

With a list of pets for each person, it should be easy to do your math: 通过列出每个人的宠物清单,可以轻松进行数学计算:

for owner,pet_list in pets.items():
    npets = len(pet_list)
    avg_age = sum([pet['Age'] for pet in pet_list]) / npets

The advice in Austin's answer the seperate reader for csv files I replace it one function and call it read_csv . 奥斯汀的建议回答了单独的csv文件阅读器,我将其替换为一个函数,并将其read_csv The average_age function do a lot of work. average_age函数做了很多工作。 If there is somewhere you don't understand please let me know to explain it. 如果有您不懂的地方,请告诉我来解释。

I think this is your solution (I'm not good at in English so I have not explain deeply); 我认为这是您的解决方案(我的英语不好,所以我没有深入解释);

import csv

def read_csv(filename):
    with open(filename, 'r') as file:
        input_file = csv.DictReader(file, delimiter=";")

        results = []
        for line in input_file:
            results.append(line)

    return results

def get_age(animal_name): 
    # the function calculate the age of given animal
    for a in animal_age:
        if a['Name of the animal'] == animal_name:
            return int(a['Age'])

def average_age(owners_animal):
    # the function return a list which contain all owners and its animals' average age
    results = []
    owners_list = []
    animal_list = []
    for o in owners_animal:
        if o['Owners Name'] not in owners_list:
            owners_list.append(o['Owners Name'])
            result = {'Owners Name': o['Owners Name'], 'Ages': []}
            age = get_age(o['Name of the animal']) or 0
            result['Ages'].append(age)

            results.append(result)
        else:
            for r in results:
                if r['Owners Name'] == o['Owners Name']:
                    r['Ages'].append(get_age(o['Name of the animal']))

    results = [{'Owners Name': obj.get('Owners Name'), 'Average age': int(sum(obj['Ages'])/len(obj['Ages']))} for obj in results]
    print(results)



owners_animal = read_csv("tabel_owners.csv") # the owner table
animal_age = read_csv("tabel_animals.csv") # the animal table

average_age(owners_animal)

There is a misvalue for Ana 's animal, Michelangelo doesn't appear in Age table. Ana的动物的价值不正确, Michelangelo没有出现在Age表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM