[Tutor] A dictionary question
Martin A. Brown
martin at linux-ip.net
Tue Nov 16 01:11:42 EST 2021
Hello,
> Just a quick one while I stop for afternoon tea.
>
> Using the example provide by Mats, if I print(pairs) I get:
>
> Counter({(4, 6): 2, (3, 4): 1, (3, 6): 1 etc.
>
> How would I print the pairs so they look like this:
>
> (4,6) 2
> (3,4) 1
> (3,6) 1
The collections.Counter behaves like a dictionary. Same methods
should work. So, try something like these basic loops that take
advantage of the items() method.
c = Counter({(4, 6): 2, (3, 4): 1, (3, 6): 1})
# -- loop through all of the key, value items in the dict-like object
for k, v in c.items():
print( k, v)
# -- same but only print where the counter for that entry is 2
for k, v in c.items():
if v == 2:
print( k, v)
Good luck, enjoy the tea (for a change of pace) and leave your
dictionaries cleaner than when you arrived. Only you can stop code
rot!
-Martin
> My feeble attempt is under the example code. I have looked at a couple of
> collections tutorials but I cannot relate what I'm seeing to the example
> below.
>
> I'm also wondering how I might do something like this:
>
> if count == 2:
>
> do this
>
> row = [{7,3},{5},{4,6,8},{7,8},{1},{9,3},{7,9},{4,6,3},{2}]
> #row = [{5},{6},{3},{4,7,5},{1,2,4,5},{1,7,5},{1,2,4,7,9},{8},{1,2,4,7,9}]
>
> set_list = [{1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 8}, {1, 9},
> {2, 3}, {2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9},
> {3, 4}, {3, 5}, {3, 6}, {3, 7}, {3, 8}, {3, 9},
> {4, 5}, {4, 6}, {4, 7}, {4, 8}, {4,9},
> {5, 6}, {5, 7}, {5, 8}, {5, 9},
> {6, 7}, {6, 8}, {6, 9},
> {7, 8}, {7, 9},
> {8, 9}
> ]
>
> from collections import Counter
>
> pairs = Counter()
>
> for s in set_list:
> for r in row:
> if s.issubset(r):
> pairs[tuple(sorted(s))] += 1
>
> print(pairs)
>
> for i in range(9):
> print(pairs[i])
>
>
(Repeated/resent from the correct email address.)
--
Martin A. Brown
http://linux-ip.net/
More information about the Tutor
mailing list