Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary comprehension destroys list of keys

I am trying to implement a ranked voting system in Python. I have this code:

import numpy as np
import itertools

candidates = ['Bob', 'Alice', 'Jim', 'Sarah', 'Paul', 'Jordan']

votes = np.matrix(
    '1 2 5 3 4 6;' \
    '1 2 3 4 5 6;' \
    '5 1 2 4 3 6;' \
    '6 2 1 3 4 5;' \
    '4 3 2 1 5 7'
    )

pairs = itertools.combinations(candidates, 2)  # All pairs of candidates

d = dict.fromkeys(pairs, 0)

for pair in pairs:
    print(pair)

The dictionary is:

d
=> {('Paul', 'Jordan'): 0, ('Alice', 'Sarah'): 0, ('Alice', 'Jim'): 0, ('Alice', 'Paul'): 0, ('Jim', 'Sarah'): 0, ('Sarah', 'Paul'): 0, ('Bob', 'Alice'): 0, ('Bob', 'Jordan'): 0, ('Jim', 'Jordan'): 0, ('Jim', 'Paul'): 0, ('Sarah', 'Jordan'): 0, ('Bob', 'Paul'): 0, ('Bob', 'Sarah'): 0, ('Bob', 'Jim'): 0, ('Alice', 'Jordan'): 0}

Which is what I want. But doing this seems to destroy the list of tuples, pairs.

If I take out the dictionary line, the code outputs:

('Bob', 'Alice')
('Bob', 'Jim')
('Bob', 'Sarah')
('Bob', 'Paul')
('Bob', 'Jordan')
('Alice', 'Jim')
('Alice', 'Sarah')
('Alice', 'Paul')
('Alice', 'Jordan')
('Jim', 'Sarah')
('Jim', 'Paul')
('Jim', 'Jordan')
('Sarah', 'Paul')
('Sarah', 'Jordan')
('Paul', 'Jordan')

With the dictionary line, nothing prints out.

I also tried a dictionary comprehension

d = {pair: 0 for pair in pairs}

And the same thing occurred. Why is the pairs list being destroyed?

like image 736
Vermillion Avatar asked Jan 06 '23 02:01

Vermillion


1 Answers

what you have with pairs is a generator not a typical list of tuples. passing a generator to dict.fromkeys is valid because it is iterable, however after iterating over pairs once, a StopIteration is called when you try to iterate again to print them

you could cast pairs to a list at creation by adding:

pairs = list(itertools.combinations(candidates, 2))

like image 107
Aaron Avatar answered Jan 13 '23 13:01

Aaron