Skip to content Skip to sidebar Skip to footer

How Does A Python Genius Iterate Over A Single Value In A Python Tuple?

I have a dictionary named 'score' with keys that are tuples. Each tuple is of the form (x, y, tag). Some possible score initializations are: score[(0, 1, 'N')] = 1.0 score[(0, 1, '

Solution 1:

[tag for x,y,tag in score if x==0 and y==1]

Solution 2:

What about a list comprehension:

[ x[2] forxin score.keys() if x[0:2] == (0,1)]

Solution 3:

You'll have to iterate over all elements and check if they key matches what you are looking for. However, you can do this nicely by using a filtered iterator:

elems = (item for item in score.iteritems() if item[0][:2] == (0, 1))

You could also use an iterator that only gives you the tag value and the element instead of the whole item tuples:

elems = ((item[0][2], item[1]) for item in score.iteritems() if item[0][:2] == (0, 1))

If you really just need the tag values and not the corresponding elements, you can do it even easier:

tags = [k[2] for k in score if k[:2] == (0, 1)]

Demo:

>>> score
{(0, 1, 'NP'): 1.2,
 (0, 1, 'V'): 1.5,
 (1, 2, 'N'): 0.2,
 (1, 2, 'PP'): 0.1,
 (1, 2, 'V'): 0.1}

>>> list(item for item in score.iteritems() if item[0][:2] == (0, 1))
[((0, 1, 'NP'), 1.2), ((0, 1, 'V'), 1.5)]

>>> list(((item[0][2], item[1]) for item in score.iteritems() if item[0][:2] == (0, 1)))
[('NP', 1.2), ('V', 1.5)]

>>> [k[2] for k in score if k[:2] == (0, 1)]
['NP', 'V']

Solution 4:

My IQ is over 200 so I hope this counts:

score = {}
score[(0, 1, 'N')] = 1.0
score[(0, 1, 'V')] = 1.5
score[(0, 1, 'NP')] = 1.2
score[(1, 2, 'N')] = 0.2
score[(1, 2, 'PP')] = 0.1
score[(1, 2, 'V')] = 0.1from itertools import groupby

defgroup_key(dict_key):
    return dict_key[:2]

sorted_keys = sorted(score)
for group_key, group_of_dict_keys in groupby(sorted_keys, key=group_key):
    print group_key
    print [(dict_key, score[dict_key]) for dict_key in group_of_dict_keys]

"""
(0, 1)
[((0, 1, 'N'), 1.0), ((0, 1, 'NP'), 1.2), ((0, 1, 'V'), 1.5)]
(1, 2)
[((1, 2, 'N'), 0.2), ((1, 2, 'PP'), 0.1), ((1, 2, 'V'), 0.1)]
"""

of course if you just want the tags by themselves then change the loop:

for group_key, group_of_dict_keys in groupby(sorted_keys, key=group_key):
    print group_key
    tags = [tag for x, y, tag in group_of_dict_keys]
    print tags
"""
(0, 1)
['N', 'NP', 'V']
(1, 2)
['N', 'PP', 'V']
"""

Solution 5:

If you just want the tags then defaultdict will be the most simple option.

score = {}
score[(0, 1, 'N')] = 1.0
score[(0, 1, 'V')] = 1.5
score[(0, 1, 'NP')] = 1.2
score[(1, 2, 'N')] = 0.2
score[(1, 2, 'PP')] = 0.1
score[(1, 2, 'V')] = 0.1from collections import defaultdict

dict_ = defaultdict(list)

for x,y,tag in score:
    dict_[x,y].append(tag)

#now get a result for any x,y we like:print dict_[0,1]
"""['NP', 'N', 'V']"""

Post a Comment for "How Does A Python Genius Iterate Over A Single Value In A Python Tuple?"