Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
填充Python字典_Python_Dictionary - Fatal编程技术网

填充Python字典

填充Python字典,python,dictionary,Python,Dictionary,大家好,我正在构建一个字典,其中每个键都是客户名称,每个值都是每个客户购买的元组列表,如:(产品,数量)。例如: {'customer1': (('milk', 3), ('bread', 5), ('eggs', 2)), 'customer2': (('cheese', 2), ('cereal', 7))} 我正在根据SQL查询的结果填充字典。作为一名Python新手,有人能推荐一种“pythonic”的方法吗?查询中的每一行都包含客户名称、产品、数量。我希望您的数据库中有一个列表,例

大家好,我正在构建一个字典,其中每个键都是客户名称,每个值都是每个客户购买的元组列表,如:(产品,数量)。例如:

{'customer1': (('milk', 3), ('bread', 5), ('eggs', 2)),
 'customer2': (('cheese', 2), ('cereal', 7))}

我正在根据SQL查询的结果填充字典。作为一名Python新手,有人能推荐一种“pythonic”的方法吗?查询中的每一行都包含客户名称、产品、数量。

我希望您的数据库中有一个列表,例如

rows = [('customer1', ('milk', 2)), ('customer12', ('bread', 4))] # etc etc
然后你可以简单地做

for row in rows:
    cust_dict[row[0]] = row[1:]
这就是我要做的

from collections import defaultdict

data = (
    ('customer1', 'milk', 3),
    ('customer1', 'bread', 5),
    ('customer1', 'eggs', 2),
    ('customer2', 'cheese', 2),
    ('customer2', 'cereal', 7),
    )

result = defaultdict(list)
for name, what, amount in data:
    result[name].append((what, amount))

from pprint import pprint
result = dict(result)
pprint(result)
哪张照片

{'customer1': [('milk', 3), ('bread', 5), ('eggs', 2)],
 'customer2': [('cheese', 2), ('cereal', 7)]}

您的内部结构应该是一个列表,而不是元组,因为该结构是同质的

{'customer1': [('milk', 3), ('bread', 5), ('eggs', 2)],
 'customer2': [('cheese', 2), ('cereal', 7)]}

这还允许您对它们使用
.append()
,并且您可以使用
集合.defaultdict
以空列表开始每个值,以进一步简化。

首先,我将使用列表而不是元组作为字典条目。主要区别在于列表是可变的,而元组则不是

我认为这是解决这个问题的好办法:

from collections import defaultdict

customers = defaultdict(list)
您可以这样添加条目(当然,在您的情况下,您可以在循环中这样做):

结果是:

>>> print dict(customers)
{'customer1': [('milk', 3), ('bread', 5)], 'customer2': [('cereal', 7)]}

您可以使用内置的并将其实例化为一个列表,并在循环中附加您想要的字段,例如,如果您想要除第一个元素之外的整行,您可以执行
your_defaultdict_实例[row[0]]。附加(row[1:])
这将整洁地构建所有内容。

我想说,这在很大程度上取决于您以后将如何处理数据。你介意详细说明一下吗?到目前为止你有没有尝试过什么?是什么让你认为你的方法是“非语法的”?我将在Django网页中填充一个html表。我不确定的地方是如何对字典条目值执行.append()。您可以只处理新元素dict[“key”]=value(请参见)显然,我看不到您的数据库层返回了什么
>>> print dict(customers)
{'customer1': [('milk', 3), ('bread', 5)], 'customer2': [('cereal', 7)]}