简体   繁体   English

在 python 中将字典值附加到列表时遇到问题

[英]Having trouble appending dictionary values to list in python

Dictionary So in python I have a dictionary that is composed of a name for the key and a class object associated with the name as the object.字典所以在 python 中,我有一个字典,它由键的名称和与该名称作为对象的名称关联的类对象组成。 I need to append these objects to a list one by one from the dictionary, however when I attempt to use a for loop to do so it only appends the same object over and over agian.我需要将这些对象从字典中一个一个地附加到列表中,但是当我尝试使用 for 循环来这样做时,它只会一遍又一遍地附加相同的对象。 When I try to append dict.values(), I have them appended to a list but with the word dict_values being the first thing in the list when it should only be the values themselves.当我尝试附加 dict.values() 时,我将它们附加到一个列表中,但单词 dict_values 是列表中的第一件事,而它应该只是值本身。 Does anybody have any ideas as to how to properly append these values?有人对如何正确附加这些值有任何想法吗? I have been using我一直在使用

for value in playerDict.values():
    basicList.append(playerDict.values)
    print(basicList)

to try and append the values to the list called basicList, however every time it appends the same object and after a few iterations the list simply looks like尝试将值附加到名为 basicList 的列表中,但是每次它附加相同的对象并且经过几次迭代后,列表看起来就像

[<built-in method values of dict object at 0x103a03d48>, <built-in method values of dict object at 0x103a03d48>, <built-in method values of dict object at 0x103a03d48>, <built-in method values of dict object at 0x103a03d48>]

Where am I going wrong in appending the object values.在附加对象值时我哪里出错了。 Sorry for the basic question I am pretty new to python.对不起,我对python很陌生。

Try doing this:尝试这样做:

for value in playerDict.values():
    basicList.append(value)
    print(basicList)

Rather than:而不是:

for value in playerDict.values():
    basicList.append(playerDict.values)
    print(basicList)

When you try to append playerDict.values into the list, you were effectively trying to append value of the playerDict object in the object form and not what you stored in the key of the dictionary (and hence you were getting [<built-in method values of dict object at 0x103a03d48>, <built-in method values of dict object at 0x103a03d48> ).当您尝试将playerDict.values附加到列表中时,您实际上是在尝试以对象形式附加 playerDict 对象的值,而不是您存储在字典键中的值(因此您得到[<built-in method values of dict object at 0x103a03d48>, <built-in method values of dict object at 0x103a03d48> )。 Whereas, when you append value , it appends the actual values of the keys stored in your dictionary.而当您附加value ,它会附加存储在字典中的键的实际值。

Hope, it helps.希望,它有帮助。

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

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