Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

python 3.x - Dictionary list populating the same data 255 times

I'm having some trouble trying to yield my dictionary in every run of my "for" loop. I have a csv file that I got from ICANN and want to populate the dictionary with the data and yield each unique dictionary but after doing so and print the resulting list, I have the same dictionary 255 times. The strange thing is if I specifically print ip_data["prefix"] it will print from 000 - 255.

import csv
import re


def populate_dictionary():
    line_count = 0
    ip_data = {"prefix": "", "designation": "", "status": ""}
    ip_data_list = []

    with open("ipv4-address-space.csv") as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=",")

    for row in csv_reader:
        if line_count == 0:
            line_count += 1
        else:
            ip_data["prefix"]      = row[0]
            ip_data["designation"] = row[1]
            ip_data["status"]      = row[5]
            line_count += 1
            yield ip_data


ip_dictionary_list = populate_dictionary()
print(*ip_dictionary_list)

Even if I return a list after the looping rather than yield a dictionary, I have exactly the same issue when printing the list.

Output:

{'prefix': '255/8', 'designation': 'Future use', 'status': 'RESERVED'}
{'prefix': '255/8', 'designation': 'Future use', 'status': 'RESERVED'}
{'prefix': '255/8', 'designation': 'Future use', 'status': 'RESERVED'}
{'prefix': '255/8', 'designation': 'Future use', 'status': 'RESERVED'}
...
...
...
question from:https://stackoverflow.com/questions/65939069/dictionary-list-populating-the-same-data-255-times

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've made the code a little easier for you to debug. Do take a look and let me know if it works.

import csv
import re

def populate_dictionary():

    with open("ipv4-address-space.csv") as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=",")

    for row in csv_reader:
            yield {"prefix": row[0], "designation": row[1], "status": row[5]}

ip_dictionary_list = populate_dictionary()
print(*ip_dictionary_list)

Also, try adding the newline attribute in the open function where you first open the CSV file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...