简体   繁体   中英

How do I create add new items to a dictionary while in a loop?

I'm writing a program that reads names and statistics related to those names from a file. Each line of the file is another person and their stats. For each person, I'd like to make their last name a key and everything else linked to that key in the dictionary. The program first stores data from the file in an array and then I'm trying to get those array elements into the dictionary, but I'm not sure how to do that. Plus I'm not sure if each time the for loop iterates, it will overwrite the previous contents of the dictionary. Here's the code I'm using to attempt this:

f = open("people.in", "r")

tmp = None
people

l = f.readline()
while l:
        tmp  = l.split(',')
        print tmp
        people = {tmp[2] : tmp[0])
        l = f.readline()

people['Smith']

The error I'm currently getting is that the syntax is incorrect, however I have no idea how to transfer the array elements into the dictionary other than like this.

Use key assignment:

people = {}

for line in f:
    tmp = l.rstrip('\n').split(',')
    people[tmp[2]] = tmp[0]

This loops over the file object directly, no need for .readline() calls here, and removes the newline.

You appear to have CSV data; you could also use the csv module here:

import csv

people = {}

with open("people.in", "rb") as f:
    reader = csv.reader(f)
    for row in reader:
        people[row[2]] = row[0]

or even a dict comprehension:

import csv

with open("people.in", "rb") as f:
    reader = csv.reader(f)
    people = {r[2]: r[0] for r in reader}

Here the csv module takes care of the splitting and removing newlines.

The syntax error stems from trying close the opening { with a ) instead of } :

people = {tmp[2] : tmp[0])  # should be }

If you need to collect multiple entries per row[2] value, collect these in a list; a collections.defaultdict instance makes that easier:

import csv
from collections import defaultdict

people = defaultdict(list)

with open("people.in", "rb") as f:
    reader = csv.reader(f)
    for row in reader:
        people[row[2]].append(row[0])

In repsonse to Generalkidd's comment above, multiple people with the same last time, an addition to Martijn Pieter's solution, posted as an answer for better formatting:

import csv

people = {}

with open("people.in", "rb") as f:
    reader = csv.reader(f)
    for row in reader:
        if not row[2] in people:
            people[row[2]] = list()
        people[row[2]].append(row[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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