How to check if tuple key contains an element in dictionary - python

I am looking for an operation that could do something similar to this:
dict[ ( tuple[0] , _ ) ]
The dictionary contains tuples as keys.
How do I check if the dictionary contains a value where the tuple key has a specific value as the first part and any value as the second part?

Try this,
#Dictionary with tuples as keys
dict_with_tup = dict([((1,2),3), ((1,4),2), ((2,5),7)])
#value that you wanna find (just the first value of the tuple)
x = 1
#filtered dict based on that value
{k:v for k,v in dict_with_tup.items() if k[0]==x}
{(1, 2): 3, (1, 4): 2}

for a dictionary d
x = # value of interest
for key in d.keys():
if key[0] == x:
#do stuff
but as khelwood noted in the comments, it's not a very efficient way of doing things

Related

Comparing element inside value of a key in a dictionary is equal to the next key

d = {
0:{1,2,3},
1:{567},
2:{2,3,5,8},
3:{4,5,7,9},
4:{6,7,8}
}
I would like to compare the value of the first k-v pair with the key of the next k-v pair.
Example:
To check if 1 exists in {1,2,3} or 2 exists in {567}
If it does exist then I would like to delete the k that exists in the value.
Output should look like:
d = {
0:{1,2,3},
2:{2,3,5,8}
}
I have tried using dictionary iterators with various permutations and combinations, but with no result. What would be the best way to achieve the result?
Python dictionary are not ordered, so I'm not sure you can really speak of "next" of "previous" here. Using a pandas Series would be more appropriate.
However, you can still iterate over the keys and define this as your order.
previous = {}
dict_items = list(d.items())
for k,v in dict_items:
if k in previous:
del d[k]
previous = v
EDIT: to make sure the keys are in the correct order, changing dict_items with:
dict_items = sorted(d.items(),key=lambda x:x[0])
would do it
Guessing by your example and requirement, you're on Python 3.6+, where dicts keep insertion orders. You can do:
In [57]: d = {
...: 0:{1,2,3},
...: 1:{567},
...: 2:{2,3,5,8},
...: 3:{4,5,7,9},
...: 4:{6,7,8}
...: }
# Get an iterator from dict.keys
In [58]: keys_iter = iter(d.keys())
# Get the first key
In [59]: first_key = next(keys_iter)
# Populate output dict with first key-value
In [60]: out = {first_key: d[first_key]}
# Populate out dict with key-values based on condition by
# looping over the `zip`-ed key iterator and dict values
In [61]: out.update({k: d[k] for k, v in zip(keys_iter, d.values())
if k not in v})
In [62]: out
Out[62]: {0: {1, 2, 3}, 2: {2, 3, 5, 8}}
It took me awhile to figure out what you wanted. Below, I have re-worded your example:
EXAMPLE:
Suppose the input dictionary is as follows:
0:{1,2,3},
1:{567},
2:{2,3,5,8},
3:{4,5,7,9},
4:{6,7,8}
We have...
key of 0:{1,2,3} is 0
value of 0:{1,2,3} is {1,2,3}
key of 2:{2,3,5,8} is 2
value of 2:{2,3,5,8} is {2,3,5,8}
We execute code similar to the following:
if key of 1:{567} in value of 0:{1,2,3}:
# if 1 in {1,2,3}:
delete 1:{567}
if key of 2:{2,3,5,8} in value of 1:{567}:
# if 2 in {567}:
delete 2:{2,3,5,8}
and so on...
"""
The following code should accomplish your goal:
def cleanup_dict(in_dict):
# sort the dictionary keys
keys = sorted(indict.keys())
# keys_to_delete will tell us whether to delete
# an entry or not
keys_to_delete = list()
try:
while True:
prv_key = next(keys)
nxt_key = next(keys)
prv_val = in_dict[prv_key]
if (nxt_key in prv_val):
keys_to_delete.append(nxt_key)
except StopIteration:
pass
for key in keys_to_delete:
del in_dict[key]
return

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/

Add values to dict and increase list item's value by 1 if key is already in dict (python)

Adding values to a dict and using a simple if statement to + 1 to the value if the key exists works fine with the following:
d = {word: (frequency, wordList[1]) for frequency, word in sorteddict}
for key, value in d.items():
my_dict[key, value] = my_dict[key, value] + 1 if key in my_dict else value
I want to iterate over the dict "d" adding all the key value pairs to the dict "my_dict".
The problem I am having is that the dict's are key : list pairs and I only want to increase the value of list[0] if the key exists. For example:
d = {'smith': (1, 'jones')}
my_dict = {'smith': (2, 'jones')}
my_dict already contains the key 'smith' and so the logic would be:
+ 1 to list[0] else 1
to clarify the question and answer:
the problem is that there are 2 dicts d, my_dict. each values is a tuple containing 2 items. what we want is to generate a new dict which has the keys and values of d but with the first item of the value tuple increased by 1 if the key exists in my_dict or set to 1 if it doesn't. we will achieve that like this:
{x: (y[0] + 1 if x in my_dict else 1, y[1]) for x, y in d.items()}

Sort list of dictionaries based on keys

I want to sort a list of dictionaries based on the presence of keys. Let's say I have a list of keys [key2,key3,key1], I need to order the list in such a way the dictionary with key2 should come first, key3 should come second and with key1 last.
I saw this answer (Sort python list of dictionaries by key if key exists) but it refers to only one key
The sorting is not based on value of the 'key'. It depends on the presence of the key and that too with a predefined list of keys.
Just use sorted using a list like [key1 in dict, key2 in dict, ...] as the key to sort by. Remember to reverse the result, since True (i.e. key is in dict) is sorted after False.
>>> dicts = [{1:2, 3:4}, {3:4}, {5:6, 7:8}]
>>> keys = [5, 3, 1]
>>> sorted(dicts, key=lambda d: [k in d for k in keys], reverse=True)
[{5: 6, 7: 8}, {1: 2, 3: 4}, {3: 4}]
This is using all the keys to break ties, i.e. in above example, there are two dicts that have the key 3, but one also has the key 1, so this one is sorted second.
I'd do this with:
sorted_list = sorted(dict_list, key = lambda d: next((i for (i, k) in enumerate(key_list) if k in d), len(key_list) + 1))
That uses a generator expression to find the index in the key list of the first key that's in each dictionary, then use that value as the sort key, with dicts that contain none of the keys getting len(key_list) + 1 as their sort key so they get sorted to the end.
How about something like this
def sort_key(dict_item, sort_list):
key_idx = [sort_list.index(key) for key in dict_item.iterkeys() if key in sort_list]
if not key_idx:
return len(sort_list)
return min(key_idx)
dict_list.sort(key=lambda x: sort_key(x, sort_list))
If the a given dictionary in the list contains more than one of the keys in the sorting list, it will use the one with the lowest index. If none of the keys are present in the sorting list, the dictionary is sent to the end of the list.
Dictionaries that contain the same "best" key (i.e. lowest index) are considered equal in terms of order. If this is a problem, it wouldn't be too hard to have the sort_key function consider all the keys rather than just the best.
To do that, simply return the whole key_idx instead of min(key_idx) and instead of len(sort_list) return [len(sort_list)]

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

Categories