简体   繁体   中英

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() .

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. The sum(..) with generator trick efficiently counts all values of the contained per-row dictionary where the value equals 'available' .

Result:

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

To show available seats for a specific row you filter and just use 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:

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 :

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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