Houman
Houman

Reputation: 66320

How to combine initialization and assignment of dictionary in Python?

I would like to figure out if any deal is selected twice or more.

The following example is stripped down for sake of readability. But in essence I thought the best solution would be using a dictionary, and whenever any deal-container (e.g. deal_pot_1) contains the same deal twice or more, I would capture it as an error.

The following code served me well, however by itself it throws an exception...

    if deal_pot_1:
       duplicates[deal_pot_1.pk] += 1

    if deal_pot_2:
        duplicates[deal_pot_2.pk] += 1

    if deal_pot_3:
        duplicates[deal_pot_3.pk] += 1

...if I didn't initialize this before hand like the following.

    if deal_pot_1:
       duplicates[deal_pot_1.pk] = 0

    if deal_pot_2:
        duplicates[deal_pot_2.pk] = 0

    if deal_pot_3:
        duplicates[deal_pot_3.pk] = 0

Is there anyway to simplify/combine this?

Upvotes: 0

Views: 151

Answers (5)

user1277476
user1277476

Reputation: 2909

A set is probably the way to go here - collections.defaultdict is probably more than you need.

Don't forget to come up with a canonical order for your hands - like sort the cards from least to greatest, by suit and face value. Otherwise you might not detect some duplicates.

Upvotes: 0

Kijewski
Kijewski

Reputation: 26022

So you only want to know if there are duplicated values? Then you could use a set:

duplicates = set()
for value in values:
    if value in duplicates():
        raise Exception('Duplicate!')
    duplicates.add(value)

If you would like to find all duplicated:

maybe_duplicates = set()
confirmed_duplicates = set()

for value in values:
    if value in maybe_duplicates():
        confirmed_duplicates.add(value)
    else:
        maybe_duplicates.add(value)

if confirmed_duplicates:
    raise Exception('Duplicates: ' + ', '.join(map(str, confirmed_duplicates)))

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838216

It looks like you want collections.Counter.

Upvotes: 3

Sven Marnach
Sven Marnach

Reputation: 601619

There are basically two options:

  1. Use a collections.defaultdict(int). Upon access of an unknown key, it will initialise the correposnding value to 0.

  2. For a dictionary d, you can do

    d[x] = d.get(x, 0) + 1
    

    to initialise and increment in a single statement.

Edit: A third option is collections.Counter, as pointed out by Mark Byers.

Upvotes: 3

BrenBarn
BrenBarn

Reputation: 251383

Look at collections.defaultdict. It looks like you want defaultdict(int).

Upvotes: 1

Related Questions