从defaultdict打印值

时间:2018-08-07 08:27:36

标签: python python-3.x

我正在写一些看起来像这样的代码:

for i in range(len(A)):
    A[i].extend(B)

这将给我一个defaultdict,其密钥为def check_states(inventory): inventory_list = defaultdict(list) for i in inventory: inventory_list[i['store_site']].append(i) ,并列出了所有清单中的所有清单,这些清单中包含的数据是信息,如接收日期,转让日期,序列号,状态等。因此它是一个字典,它映射到其中的多个值。因此,我们所拥有的是词典列表的词典。。我要打印一些值,但不是全部。因此,在上述功能的末尾,我添加:

store_site

我明白了

for store in inventory_list:
    print(store['serial_id'])

我也尝试使用TypeError: string indices must be integers.

items()

我明白了

for store in inventory_list.items():
    print(store['serial_id'])

有人可以帮我看看我的错误吗?我也在寻找类似的问题,但是大多数词典问题都是关于打印1:1值,而不是1:many值。

TypeError: tuple indices must be integers, not str.

2 个答案:

答案 0 :(得分:1)

您的第一行代码

for store in inventory_list:
    print(store['serial_id'])

引发错误,因为for k in dictionary遍历字典的键,将每个键设置为k。当您尝试访问store[x]时,是在告诉python访问字符串x的位置store处的字符。但是,您使用了一个字符串(serial_id,因此python告诉您它需要一个整数。

第二个片段

for store in inventory_list.items():
    print(store['serial_id'])

会产生相同的错误,但是在这种情况下,store(key, value)的元组。使用此语法的更常见方法是访问键和值,如下所示:

inventory_list = {
    'store a': { 'apples': 10, 'bananas': 5, 'cows': 2 },
    'store b': { 'apples': 5, 'bananas': 10 } }

for store, stuff in inventory_list.items():
    print( store )
    print( stuff )

返回

store a
{'apples': 10, 'bananas': 5, 'cows': 2}
store b
{'apples': 5, 'bananas': 10}

如果要遍历每个嵌套词典中的数据,请执行此操作,就像访问顶级项目一样,即

# using the same inventory list as before
for k,v in inventory_list.items():
    print("Inventory for store " + k)
    # v is a reference to a dictionary, so iterate through that
    for item, qtt in v.items():
        print("Item: " + item + "; quantity: " + str(qtt))

输出:

Inventory for store store a
Item: apples; quantity: 10
Item: bananas; quantity: 5
Item: cows; quantity: 2
Inventory for store store b
Item: apples; quantity: 5
Item: bananas; quantity: 10

如果您想直接访问嵌套字典中的数据,则可以通过按键使用:

for k,v in inventory_list.items():
    print(k + " has " + str(v['apples']) + ' apples in stock')

输出:

store a has 10 apples in stock
store b has 5 apples in stock

如果您有词典列表,则可以使用for x in list进行遍历,其中每个x都是字典:

inventory_list = [
     { 'apples': 10, 'bananas': 5, 'cows': 2 },
     { 'apples': 5, 'bananas': 10 }]

for store in inventory_list:
    print( store )

输出:

{'apples': 10, 'bananas': 5, 'cows': 2}
{'apples': 5, 'bananas': 10}

或直接访问值:

for store in inventory_list:
    print( store['apples'] )

输出:

10
5

将所有这些放在一起以在字典列表的字典中访问数据:

dd = { 'store a': [ { 'apples': 10, 'bananas': 5, 'cows': 2 }, { 'apples': 20, 'bananas': 15, 'cows': 25 } ],
      'store b': [{ 'apples': 5, 'bananas': 10 }, {'apples': 2, 'bananas': 30, 'cows': 0}] }

for k,v in dd.items():
    print(k)
    for list_item in v: # v is the list, list_item is each dictionary
        print('apples: ' + str(list_item['apples']))

输出:

store a
apples: 10
apples: 20
store b
apples: 5
apples: 2

如果有疑问,我强烈建议在您的代码中添加print语句,以弄清楚每个变量的外观(是字符串,元组还是字典等)。它将极大地帮助您理解和调试代码。

可以从reading the python documentation on dictionarieslists中收集所有这些信息。

答案 1 :(得分:0)

我认为问题不是很了解您的for循环中要迭代的数据的性质。也许不了解inventory参数中的内容。

for store in inventory_list:
    ...

inventory_listdict。如上所示,当对dict进行迭代时,将获得字典中所有keys的序列。在您的字典中,这些键是“显然” strings。我说是通过反向工程显示的错误:

TypeError: string indices must be integers.

这是运行时出现的错误:

stored = "some_name"
store['serial_id']

所以...对您来说,第一个问题是按inventory顺序理解数据。元素显然具有“ store_site”,但该值存在一个字符串,而不是某些更高级别的数据结构。

在第二个示例中:

for store in inventory_list.items():
   ...

dict上的items()方法生成一系列键/值元组。它不会生成密钥序列(我认为您等同于“商店”)。这就解释了为什么store['serial_id']会失败的原因。