简体   繁体   English

计算字典中键值对的数量

[英]counting the number of key value pairs in a dictionary

I am working with dictionaries for the first time. 我是第一次与字典合作。 I would like to know how I can count how many key value pairs there are in each dictionary where the value is 'available'. 我想知道如何计算每个“可用”字典中有多少个键值对。 I know I probably use len() . 我知道我可能使用len()

seats = {
  'A': {'A1':'available', 'A2':'unavailable', 'A3':'available'},
  'B': {'B1':'unavailable', 'B2':'available', 'B3':'available'}, 
  'C': {'C1':'available', 'C2':'available', 'C3':'unavailable'}, 
  'D': {'D1':'unavailable', 'D2':'available', 'D3':'available'} }

rowChoice = raw_input('What row? >> ')
numSeats = input('How many Seats? >> ')

I am very new to this, so I really need a very simple method and probably some annotation or explanation how it works. 我对此很陌生,所以我真的需要一个非常简单的方法,可能需要一些注释或解释它是如何工作的。

I'd use the following statement to count each nested dictionary's values: 我将使用以下语句来计算每个嵌套字典的值:

{k: sum(1 for val in v.itervalues() if val == 'available') for k, v in seats.iteritems()}

This builds a new dictionary from the same keys as seats with each value being the number of seats available. 这将使用与seats相同的键来构建新词典,每个值都是可用的座位数。 The sum(..) with generator trick efficiently counts all values of the contained per-row dictionary where the value equals 'available' . 具有生成器技巧的sum(..)有效地计算所包含的每行字典的所有值,其中值等于'available'

Result: 结果:

{'A': 2, 'C': 2, 'B': 2, 'D': 2}

To show available seats for a specific row you filter and just use len() : 要显示特定行的可用座位,您可以过滤并仅使用len()

row_available = [k for k, v in seats[rowChoice].iteritems() if v == 'available']
avail_count = len(row_available)
if avail_count:
    print 'there {is_are} {count} seat{plural} available in row {rowChoice}, seat{plural} {seats}'.format(
        is_are='are' if avail_count > 1 else 'is', count=avail_count, 
        plural='s' if avail_count > 1 else '', rowChoice=rowChoice, 
        seats=row_available[0] if avail_count == 1 else ' and '.join([', '.join(row_available[:-1]), row_available[-1]]))

For rowChoice = 'A' this prints: 对于rowChoice = 'A'将输出:

there are 2 seats available in row A, seats A1 and A3

but it adjusts to form coherent sentences for more or fewer seats too. 但它也会调整以形成连贯的句子,以容纳更多或更少的席位。

Using collections.Counter and itertools.chain : 使用collections.Counteritertools.chain

from collections import Counter
from itertools import chain

print Counter(chain.from_iterable(i.itervalues() for i in seats.itervalues()))
# Counter({'available': 8, 'unavailable': 4})

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

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