python中字典的问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中字典的问题相关的知识,希望对你有一定的参考价值。
字典已经建好了,键也好了,怎么从键盘输入值然后加入键中?
参考技术A a = input()this_dict =
this_dict["key"] = a
在腌制字典中检索单个对象的问题(Python 3)
【中文标题】在腌制字典中检索单个对象的问题(Python 3)【英文标题】:Problem retrieving individual objects in pickled dictionary (Python 3) 【发布时间】:2019-12-13 16:57:18 【问题描述】:我的程序将“食物”对象存储在字典中并存储在 csv 文件中,该文件充当数据库。我想根据命令从字典中检索单个食物对象,但是当我尝试时,我似乎只检索字典中的最后一个对象。
import pickle
class Food(object):
fooddict = dict()
def __init__(self, name, weight, calories, time):
self.name = name
self.weight = weight
self.calories = calories
self.time = time
def __str__(self):
return 'self.names'.format(self=self) + \
' weigh self.weight'.format(self=self) + \
' ounces, contain self.calories'.format(self=self) + \
' calories, and stay fresh for self.time'.format(self=self) + \
' days.'
@classmethod
def createFoodInput(cls):
name = str(input("Enter the name: "))
weight = float(input("Enter the weight: "))
calories = float(input("Enter the calories: "))
time = float(input("Enter how many days it can store for: "))
return cls(name, weight, calories, time)
def storeFoodDict(f):
fooddict = Food.retreiveFoodDict()
if fooddict == "Empty File":
fooddict = dict(f.name: f)
with open("food.csv", 'wb') as filewriter:
try:
pickle.dump(fooddict, filewriter)
except:
print("Error storing pickled dictionary")
else:
food_found = False
for key in list(fooddict):
if key.__eq__(f.name):
print("Food already stored!")
food_found = True
if not food_found:
fooddict.update(f.name: f)
with open("food.csv", 'wb') as filewriter:
try:
pickle.dump(fooddict, filewriter)
except:
print("Error storing pickled dictionary")
@classmethod
def retreiveFoodDict(cls):
with open("food.csv", 'rb') as filereader:
try:
fooddict = pickle.load(filereader)
return fooddict
except EOFError:
return("Empty File")
def findFood(title):
fooddict = Food.retreiveFoodDict()
for key in list(fooddict):
if key.__eq__(title):
continue
return fooddict[key]
s = "apple"
n = findFood(s) #does not work, it returns banana instead of apple
#which is really just grabbing whatever is the
#last object in the dictionary
m = findFood("banana") #seems to work, but only because banana is the
#last object in the dictionary
print(n) #should print an apple "food object" but instead prints a banana
print(str(m.calories)) #works, but if I said n.calories it would still print
#m.calories instead
p = Food.retreiveFoodDict() #seems to work and retrieve the dictionary
print(str(p)) #also seems to work of course
控制台输出: 香蕉重 5.0 盎司,含有 120.0 卡路里,可保鲜 3.0 天。 120.0 'apple': main.Food object at 0x00D2C2E0>, 'banana': main.Food object at 0x00D36D00>
字典包含 2 个食物对象(苹果和香蕉),但 print(n) 语句显示的是香蕉,而不是苹果。谁能指出这是为什么或我误解了什么?非常感谢!
【问题讨论】:
你为什么要腌制然后放入 csv,而不是只挑选整个东西? 似乎类的格式和输出搞砸了,但你可以edit 修复它。如果需要,请参阅code formatting help。顺便说一句,欢迎来到 Stack Overflow!查看tour。另外顺便说一句,您应该创建一个minimal reproducible example。 Shelve你的果实! 腌制整件事是什么意思?每次我在字典中存储一个新对象时,我都会尝试腌制整个字典,这是我的数据库。 【参考方案1】:我找到了自己问题的答案。我在 findFood 函数中滥用了 continue 。 这段代码解决了我的问题。
def getFood(food_name):
fooddict = Food.retreiveFoodDict()
for key in list(fooddict):
if key.__eq__(food_name):
return fooddict[key]
此函数所做的只是在 csv 文件中检索对象字典并遍历键,直到找到传递的键名。如果找到,正确的键名将作为食物对象返回。我最初的错误是使用“继续”关键字来停止 for 循环,它直接在我们想要的对象之后返回对象。
【讨论】:
以上是关于python中字典的问题的主要内容,如果未能解决你的问题,请参考以下文章