Query Python dictionary to get value from tuple - python

Let's say that I have a Python dictionary, but the values are a tuple:
E.g.
dict = {"Key1": (ValX1, ValY1, ValZ1), "Key2": (ValX2, ValY2, ValZ2),...,"Key99": (ValX99, ValY99, ValY99)}
and I want to retrieve only the third value from the tuple, eg. ValZ1, ValZ2, or ValZ99 from the example above.
I could do so using .iteritems(), for instance as:
for key, val in dict.iteritems():
ValZ = val[2]
however, is there a more direct approach?
Ideally, I'd like to query the dictionary by key and return only the third value in the tuple...
e.g.
dict[Key1] = ValZ1 instead of what I currently get, which is dict[Key1] = (ValX1, ValY1, ValZ1) which is not callable...
Any advice?

Just keep indexing:
>>> D = {"Key1": (1,2,3), "Key2": (4,5,6)}
>>> D["Key2"][2]
6

Use tuple unpacking:
for key, (valX, valY, valZ) in dict.iteritems():
...
Often people use
for key, (_, _, valZ) in dict.iteritems():
...
if they are only interested in one item of the tuple. But this may cause problem if you use the gettext module for multi language applications, as this model sets a global function called _.
As tuples are immutable, you are not able to set only one item like
d[key][0] = x
You have to unpack first:
x, y, z = d[key]
d[key] = x, newy, z

Using a generator expression!
for val in (x[2] for x in dict):
print val
You don't need to use iteritems because you're only looking at the values.

Related

How to access key by value in a dictionary?

I have a dict that looks like the following:
d = {"employee": ['PER', 'ORG']}
I have a list of tags ('PER', 'ORG',....) that is extracted from the specific entity list.
for t in entities_with_tag: # it includes words with a tag such as: [PER(['Bill']), ORG(['Microsoft']),
f = t.tag # this extract only tag like: {'PER, ORG'}
s =str(f)
q.add(s)
Now I want if {'PER, ORG'} in q, and it matched with d.values(), it should give me the keys of {'PER, ORG'} which is 'employee'. I try it this but does not work.
for x in q:
if str(x) in str(d.values()):
print(d.keys()) # this print all the keys of dict.
If I understand correctly you should loop he dictionary instead of the tag list. You can check if the dictionary tags are in the list using sets.
d = {"employee": ['PER', 'ORG'],
"located": ["ORG", "LOC"]}
q = ["PER", "ORG", "DOG", "CAT"]
qset = set(q)
for key, value in d.items():
if set(value).issubset(qset):
print (key)
Output:
employee
You mean with... nothing?
for x in q:
if str(x) in d.values():
print(d.keys())
What you can do is to switch keys and values in the dict and then access by key.
tags = ('PER', 'ORG')
data = dict((val, key) for key, val in d.items())
print(data[tags])
Just be careful to convert the lists in tuples, since lists are not hashable.
Another solution would be to extract both key and value in a loop. But that's absolutely NOT efficient at all.
for x in q:
if str(x) in str(d.values()):
for key, val in d.items():
if val == x:
print(key) # this print all the keys of dict.
What you can do is make two lists. One which contains the keys and one which contains the values. Then for the index of the required value in the list with values you can call the key from the list of keys.
d = {"employee": ['PER', 'ORG']}
key_list = list(d.keys())
val_list = list(d.values())
print(key_list[val_list.index(['PER','ORG'])
Refer: https://www.geeksforgeeks.org/python-get-key-from-value-in-dictionary/

How to find a value inside a list that is inside a dictionary

I am trying to find a value inside a list that is inside a dictionary whitout using the key
and the purpose is so that i cant add the same name to the dictionary.
The dictionary looks something like this:
Dict={'1_number': ['1_name'], '2_number': ['2_name', '3_name']}
so i am trying to check if 3_name exists inside the dictionary.
Also trying to display 2_number by searching for it with 2_name, that is displaying the key by finding it with one of its values.
You can actually combine list comprehension to iterate over the values of a dictionary with any for short circuit evaluation to search an item to get the desired result
>>> any('3_name' in item for item in Dict.values())
True
alternatively, if you are interested to return all instances of dictionaries which have the concerned item, just ensure that the condition to check the item in its value is within the if statement and key value pair is returned as part of the filter List Comprehension
>>> [(k, v) for k, v in Dict.items() if '3_name' in v]
[('2_number', ['2_name', '3_name'])]
Finally, if you are sure there is one and only one item, or you would like to return the first hit, use a generator with a next
>>> next((k, v) for k, v in Dict.items() if '3_name' in v)
('2_number', ['2_name', '3_name'])
You can iterate of the values of a dictionary and check for the pressence of the wanted list value:
>>> def find_in_dict(d, name):
>>> for k,vals in d.iteritems():
>>> if name in vals:
>>> return k
>>> else:
>>> return False
>>> find_in_dict(d,'3_name')
'2_number'
>>> find_in_dict(d,'4_name')
False
You can use a list comprehension to search the values of the dictionary, then return a tuple of (key, value) if you find the key corresponding to the value you are searching for.
d = {'1_number': ['1_name'], '2_number': ['2_name', '3_name']}
search = '3_name'
>>> [(key, value) for key, value in d.items() if search in value]
[('2_number', ['2_name', '3_name'])]

Dict comprehension, tuples and lazy evaluation

I am trying to see if I can pull off something quite lazy in Python.
I have a dict comprehension, where the value is a tuple. I want to be able to create the second entry of the tuple by using the first entry of the tuple.
An example should help.
dictA = {'a': 1, 'b': 3, 'c': 42}
{key: (a = someComplexFunction(value), moreComplexFunction(a)) for key, value in dictA.items()}
Is it possible that the moreComplexFunction uses the calculation in the first entry of the tuple?
You could add a second loop over a one-element tuple:
{key: (a, moreComplexFuntion(a)) for key, value in dictA.items()
for a in (someComplexFunction(value),)}
This gives you access to the output of someComplexFunction(value) in the value expression, but that's rather ugly.
Personally, I'd move to a regular loop in such cases:
dictB = {}
for key, value in dictA.items():
a = someComplexFunction(value)
dictB[key] = (a, moreComplexFunction(a))
and be done with it.
or, you could just write a function to return the tuple:
def kv_tuple(a):
tmp = someComplexFunction(a)
return (a, moreComplexFunction(tmp))
{key:kv_tuple(value) for key, value in dictA.items()}
this also gives you the option to use things like namedtuple to get names for the tuple items, etc. I don't know how much faster/slower this would be though... the regular loop is likely to be faster (fewer function calls)...
Alongside Martijn's answer, using a generator expression and a dict comprehension is also quite semantic and lazy:
dictA = { ... } # Your original dict
partially_computed = ((key, someComplexFunction(value))
for key, value in dictA.items())
dictB = {key: (a, moreComplexFunction(a)) for key, a in partially_computed}

How can you print a key given a value in a dictionary for Python?

For example lets say we have the following dictionary:
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
How can you print a certain key given its value?
print(dictionary.get('A')) #This will print 4
How can you do it backwards? i.e. instead of getting a value by referencing the key, getting a key by referencing the value.
I don't believe there is a way to do it. It's not how a dictionary is intended to be used...
Instead, you'll have to do something similar to this.
for key, value in dictionary.items():
if 4 == value:
print key
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for instance the 2nd key which is at position 1)
print([key for key in x.keys()][1])
Output:
Y
The dictionary is organized by: key -> value
If you try to go: value -> key
Then you have a few problems; duplicates, and also sometimes a dictionary holds large (or unhashable) objects which you would not want to have as a key.
However, if you still want to do this, you can do so easily by iterating over the dicts keys and values and matching them as follows:
def method(dict, value):
for k, v in dict.iteritems():
if v == value:
yield k
# this is an iterator, example:
>>> d = {'a':1, 'b':2}
>>> for r in method(d, 2):
print r
b
As noted in a comment, the whole thing can be written as a generator expression:
def method(dict, value):
return (k for k,v in dict.iteritems() if v == value)
Python versions note: in Python 3+ you can use dict.items() instead of dict.iteritems()
target_key = 4
for i in dictionary:
if dictionary[i]==target_key:
print(i)
Within a dictionary if you have to find the KEY for the highest VALUE please do the following :
Step 1: Extract all the VALUES into a list and find the Max of list
Step 2: Find the KEY for the particular VALUE from Step 1
The visual analyzer of this code is available in this link : LINK
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
lis=dictionary.values()
print(max(lis))
for key,val in dictionary.items() :
if val == max(lis) :
print("The highest KEY in the dictionary is ",key)
I think this is way easier if you use the position of that value within the dictionary.
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
# list out keys and values separately
key_list = list(dictionary.keys())
val_list = list(dictionary.values())
# print key with val 4
position = val_list.index(4)
print(key_list[position])
# print key with val 6
position = val_list.index(6)
print(key_list[position])
# one-liner
print(list(my_dict.keys())[list(my_dict.values()).index(6)])
Hey i was stuck on a thing with this for ages, all you have to do is swap the key with the value e.g.
Dictionary = {'Bob':14}
you would change it to
Dictionary ={1:'Bob'}
or vice versa to set the key as the value and the value as the key so you can get the thing you want

Calling a function from a string (key[:-1]())

Basically I have a list of key:items in a dictionary, and I am using a loop to find the key that matches the item I get, and I have functions for every key. The keys are numbered though, so I need to take off the last number.
This leaves me with needing to call a function from a string like the one in the subject:
key[-1]()
key[-1] actually is a string that returns something like scalcs, and that is the name of a function of mine that I then need to call.
I've searched around and have seen stuff about classes. I'm new and honestly have never worked with classes at all and have a lot of code and a lot of these functions. I would rather not do that method if at all possible.
d = {key1: item1, key2: item2, akey1: item3, akey2: item4, dkey1: item1, dkey2: item2}
I want to call key, akey, or dkey when my value matches that of the value attached to the key in the dictionary.
So I will loop through d like this:
for key, value in d.items():
if id == value:
print key[:-1]
Now I just need to call that key[:-1]
def hello_world():
print "hello world"
d = {'hello':hello_world}
d['hello']()
locals()['hello_world']()
I'm not entirely sure that I understand your question. Is the following right?
You have dictionaries
d1 = {key1: item1, key2: item2, ...}
and
d2 = {key1: function1, key2: function2, ...}
Given an item item2, you want to find function2.
If that's it, then you should store the information you have differently, in the form
d = {item1: function1, item2: function2, ...}
The function you want is then d[item2].
To generate d from d1 and d2, you can do
d = {item: d2[key] for key, item in d1.items()}
Instead of storing the name of your function as key of your dictionary, you could try to store the function itself:
>>> f = lambda x:x+1
>>> g = lambda x:x-1
>>> D = {f:'0', g:'1'}
>>> (F,) = [k for k,v in D.items() if v=="0"]
>>> F(3)
4
If you need to keep your keys as strings, then create a second dictionary (key_as_string, corresponding_function) with all the correspondences and just retrieve the function corresponding to the key you got at the previous step.
Note that you need to be very careful that you don't have multiple keys with the same value, otherwise, there's no telling that you'll get a unique function. The safest way would be to build a reverse dictionary of what you have: (some_string_index, a_function).
Note also that the function is just an object: in the example above, I used something very simple like a lambda, but you could use something far more complicated:
def a_function(...):
...
your_dictionary = {a_function: your_index}
safer_dictionary = {your_index: a_function}

Categories