我想基于JamBarcode创建一个新文件,该文件从JamPrice中查找价格,从JamDetails中查找其余信息并将其放入新文件中。
我(现在)有两个词典,如下所示:
JamPrice = {
"JamBarcode": "1234", "Price": "1",
} print JamPrice
和
JamDetails = {
"JamBarcode": "1234", "Colour": "red", "Size": "small"
} print JamDetails
这是正确使用的数据结构,我是以正确的方式进行的,还是有更容易的方法?我一直在寻找http://www.pythonforbeginners.com/dictionary/how-to-use-dictionaries-in-python来帮忙。
答案 0 :(得分:1)
从概念上讲,我将这些分成数据库中的两个表:产品信息和产品零售信息。后者应该包含出售项目所需的所有信息,除了零售价格之外,可能会有类似于哪个部门的数量,销售的单位数量,对产品(它是酒精吗?你需要年龄验证销售吗?)
后者还应该包含一个指向前者的外键,或者在字典的情况下应该包含一些匹配的信息(例如条形码,就像你有的那样)。
答案 1 :(得分:1)
我认为您需要两个数据:products
和prices
这些是由条形码链接的。然后他们可以独立变化:
products = {
"1234": dict(name="jam", colour="red", size="small")
"5678": dict(name="marmalade", colour="orange", size="medium")
}
prices = {
"1234": "1.5",
"5678": "1.75"
}
答案 2 :(得分:0)
我建议将所有果酱细节合并到统一字典中,并使用JamBarcode访问内容。换句话说,实际上存在与字典内的每个条形码键相关联的对象。
e.g。
# create a dictionary called jam:
jam_dictionary = {}
# insert items into your dictionary using index notation:
jam_dictionary['1234'] = {'Colour': 'red', 'Size': 'small', 'Price': '1'}
# you can also use the index key to retrieve the information
print(jam_dictionary['1234'])
# {'Colour': 'red', 'Size': 'small', 'Price': '1'}
# and specific sub-fields
print(jam_dictionary['1234']['Colour'])
# red
jam_dictionary['1234']['Colour'] = 'blue'
print(jam_dictionary['1234']['Colour'])
# blue
您还可以像这样构建字典:
jam_dictionary = {
'1234': {'Colour': 'red', 'Size':'small', 'Price': '1'},
'5678': {'Colour': 'blue', 'etc':'etc'}
}
但这更复杂,因为你可能会在字典创建后添加或删除内容,所以你也可以这样做。
如果您可以从处理或处理数据的相关功能中受益,那么您应该开始考虑可能创建Jam类
答案 3 :(得分:0)
在我看来,你真的想要一组Jams,并且你正在使用条形码信息来跟踪你特别引用的那个。
在我看来,你会有一个词典:
Jams = { '1234':[1, "red", "small"]}
然后,您可以使用条形码作为密钥为dict添加更多卡纸。
你在这本书中对“得到”这一点还不够,但你会发现将列表中的信息保持为“正确”_会变得棘手,你会想要使用“命名元组”而不是
import collections
JamTuple = collections.namedtuple('Jam', ['barcode', 'price', 'color', 'size'])
a_jam = JamTiuple(1234, price=1,color='red', size='Small')
JamsDict = {1234:a_jam}
但实际上,这很大程度上取决于你接下来要做什么。