abcdef123
abcdef123

Reputation: 11

Access dictionary value when the key is a tuple

I'm new to Python and I have a problem where I need to get the value from a dictionary where the keys are tuples. For example:

ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}

I know that each number appears ones in the keys, and I want to access the value where the key has the number 2 in (the value will be 3).

Can I get any help on how to access this value?

Upvotes: 0

Views: 4191

Answers (4)

sirfz
sirfz

Reputation: 4277

You could "flatten" the dictionary using the following comprehension:

ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}

flat = {element: value for key, value in ones.items() for element in key}

Now you can get the value of any key from the tuples via flat.

Upvotes: 3

宏杰李
宏杰李

Reputation: 12168

ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}
for key, value in ones.items():
    if 2 in key:
        print(value)

out:

3

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121834

You can't use the normal dictionary access when you are looking for one subelement of a key. You'll have to loop:

value_for_2 = next(ones[key] for key in ones if 2 in key)

would find the first match (where 'first' is arbitrary, as dictionaries are not ordered).

If your tuple elements really are unique, and you need to do multiple look-ups, then convert your dictionary first to use the tuple elements as keys instead:

converted = {t_elem: value for key in ones for t_elem in key}

Don't worry about the value duplication here. Values don't need to be unique, and all you do is store references; the above won't create copies of the values.

Now you can use fast key lookups again:

value_for_2 = converted[2]

Upvotes: 1

Hussain
Hussain

Reputation: 5177

You can iterate ones and check if 2 is present in the key

In [24]: ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}

In [25]: for k, v in ones.iteritems():
   ....:     if 2 in k:
   ....:         print v
   ....:         
3

Upvotes: 1

Related Questions