简体   繁体   English

Python字典没有返回所有它的项目

[英]Python Dictionary Not Returning All It's Items

I'm having an issue with my code were I read a text file, put the information in the file inside a list, and then convert the list into a dictionary. 我的代码有问题是我读了一个文本文件,把信息放在列表中的文件中,然后将列表转换成字典。

The problem is that when I try to print the items contained in it (be it the entire dictionary or the keys or values only), it only prints one key/value pair. 问题是,当我尝试打印其中包含的项目(无论是整个字典还是键或值)时,它只打印一个键/值对。

In fact, the dictionary only contains that particular key/value pair and nothing more. 实际上,字典只包含该特定的键/值对,仅此而已。

Here is my code: 这是我的代码:

class Babies:
    b_list = []
    b_dict = {}

    def __init__(self, scotbabies=None):  # placeholder
        self.scotbabies = scotbabies

    def read_names_from_file(self, file):
        global b_list
        global b_dict

        for line in open(file):
            b_list = line.split()
            b_dict = {k: v for k, v in (b_list for word in b_list)}
            print b_dict # if I print the dictionary at this point it will

            # print the entire dictionary. If I try to print it inside another
            # function or elsewhere, it will only print the first key/value pair.


babies = Babies()
babies.read_names_from_file('scotbabies2014.txt')

The text file contains a list of all the names of the babies born in Scotland along with their gender. 该文本文件包含苏格兰出生婴儿的所有姓名及其性别的列表。

You are redefining the entire dictionary every iteration of the loop. 您将在循环的每次迭代中重新定义整个字典。

b_dict = {k: v for k, v in (b_list for word in b_list)} reassigns b_dict to a new dictionary. b_dict = {k: v for k, v in (b_list for word in b_list)}b_dict重新分配给新字典。

You should look into the dictionary type's update function, which kind of merges two dictionaries. 您应该查看字典类型的update函数,哪种类型合并两个字典。

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

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