Getting keys and values of dictionary if key in list - python

So I have a dictionary names "ngrams_count". I want to find all keys in this dictionary that are in a list called "words_to_find". I would also like to return the values associated with those keys.
So far, this is what I'm working with
ideasrep = [key for key in words_to_find if key in ngrams_count]
That returns only the keys that are found in the word list.
I'm also looking for a way to return only the key/values pairs for which the value is greater than one. I've tried a similar technique as this:
[(key,values) for key, values in ngrams_count.items() if values > 1]
However, this only seems to work if I stay within the dictionary and I'm running out of ideas... Ideally, I'd like a way to do these two things simultaneously.

Your first version is almost right, you just need to add ngrams_count[key] to the result.
ideasrep = [(key, ngrams_count[key]) for key in words_to_find if key in ngrams_count]
Or you can use the second version, but change the condition to check if the key is in words_to_find.
[(key,values) for key, values in ngrams_count.items() if key in words_to_find]
If words_to_find is big, you should convert it to a set before the list comprehension to make the second version more efficient.

Related

How can I handle only the first part of my value list of a dictionary in Python?

I have a dictionary which has a list of values and I want to use only the first value of each pair before the first comma. Is that possible?
If you came across anything similar please write it down
The output you expect is unclear. If you want a dictionary in which you only keep the first item of the sublist, use a dictionary comprehension:
Assuming dic1 the input.
dic2 = {k:v[0][0] for k,v in dic1.items()}
if you have a dictionary d, then use
d.keys() to return the keys of your dictionary, which is the first item in each key value pair that makes up a dictionary
It's definitely possible.
I'll assume for now that by: "I want to use only the first value of each pair",
you mean you want to extract the first value of each pair from the dict.
Now, the answer to that depends slightly on what you ment by "pair".
If you ment the items you can get out of the items method on the dict, then the simplest way to get the first element of each of these pairs would be the keys method, also directly on the dict. In code:
def get_fist_from_pair(d: dict):
return d.keys()
In the image you provided, the values stored in the dict are lists of each length 1, filled with another list. If this inner list is what you ment by "pairs", the code would be slightly different:
def get_fist_from_pair(d: dict):
return [v[0][0] for v in d.values()]
This code looks at each value and extracts the first element of the inner list.
In case that this interpretation of pair is correct, but you also want to associate the key with that element in a new dict, the code for it would be:
def get_first_from_pair(d: dict):
return {key: d[key][0][0] for key in d}

Invert a dictionary inplace

I have a dictionary with unique values and I want to invert it (i.e. swap keys with values) inplace.
Is there any way doing it without using another dictionary?
I would prefer to just manipulate the items inside the dict than use a new dictionary, so that id(my_dict) would remain the same.
If you are trying to swap keys and values and do not mind duplicate values creating key conflicts, you can "reverse" the dictionary rather easily with a single line of code:
dictionary = dict(map(reversed, dictionary.items()))
If you would rather use the dictionary comprehension syntax instead, you can write this line:
dictionary = {value: key for key, value in dictionary.items()}
If you do not want to use the items method of the dictionary, it is rather easy to avoid:
dictionary = {dictionary[key]: key for key in dictionary}
If you can afford creating a copy of the dictionary, you can reverse it in place if needed:
def reverse_in_place(dictionary):
reference = dictionary.copy()
dictionary.clear()
dictionary.update(map(reversed, reference.items()))
I guess you want to swap the keys and the values of the dict?
You can do it like this:
dict_name = dict(zip(dict_name.values(), dict_name.keys()))

search a dict keys in python

How do I search a dictionary of bigrams for a key if it exists or not and print it's value if does?
wordsCounts = {('the','computer'): 2 , ('computer','science'): 3 , ('math','lecture'): 4, ('lecture','day'): 2}
So, I want to search if the pair ('math','lecture') exists or not?
pair = ['computer','science']
for k in wordscount.keys():
if wordscount[k] == pair:
print wordscount[v]
So the result will be a list ('computer','science'): 3
Just test if the tuple of the pair exists:
if tuple(pair) in wordscount:
print wordscount[tuple(pair)]
There is no need to loop through all the keys in the dictionary; a python dictionary is much more efficient at finding matching keys if you just give it the key to look for, but it has to be the same type. Your dictionary keys are tuples, so look use a tuple key when searching.
In fact, in python dictionaries, lists are not allowed as keys because they are mutable; you would not be able to search for keys accurately if the keys themselves can be changed.
First you may want to know why it does not work..
for k in wordscount.keys():
if wordscount[k] == pair:
wordscount.keys() will return you list of tuple and next line is to compare value of dict wordsCount to a list 'pair.
Solution is
for k in wordscount.keys():
if k == tuple(pair):
print workscount[k]

Randomizing a dictionary in python

I know you might say that dictionaries are not in any order naturally, but I have a large dictionary keys are numbers and some string as their values. The keys start from 0. for example: x={0:'a',1:'b',2:'c'}. I am using .iteritems() to go over my dictionary in a loop. however, this is done in the exact order of the keys 0,1,2. I want this to be randomized. so for example my loop prints this: 1:'b',2:'c',0:'a'. i need help. thanks
Use random.shuffle. Also, the key iteration order of a dictionary is not guaranteed by any means - you just happened to get (0, 1, 2).
import random
keys = my_dict.keys()
random.shuffle(keys)
for key in keys:
print key, my_dict[key]

How to work around needing to update a dictionary

I need to delete a k/v pair from a dictionary in a loop. After getting RuntimeError: dictionary changed size during iteration I pickled the dictionary after deleting the k/v and in one of the outer loops I try to reopen the newly pickled/updated dictionary. However, as many of you will probably know-I get the same error-I think when it reaches the top of the loop. I do not use my dictionary in the outermost loop.
So my question is-does anyone know how to get around this problem? I want to delete a k/V pair from a dictionary and use that resized dictionary on the next iteration of the loop.
to focus the problem and use the solution from Cygil
list=[27,29,23,30,3,5,40]
testDict={}
for x in range(25):
tempDict={}
tempDict['xsquared']=x*x
tempDict['xinverse']=1.0/(x+1.0)
testDict[(x,x+1)]=tempDict
for item in list:
print 'the Dictionary now has',len(testDict.keys()), ' keys'
for key in testDict.keys():
if key[0]==item:
del testDict[key]
I am doing this because I have to have some research assistants compare some observations from two data sets that could not be matched because of name variants. The idea is to throw up a name from one data set (say set A) and then based on a key match find all the names attached to that key in the other dataset (set B). One a match has been identified I don't want to show the value from B again to speed things up for them. Because there are 6,000 observations I also don't want them to have to start at the beginning of A each time they get back to work. However, I can fix that by letting them chose to enter the last key from A they worked with. But I really need to reduce B once the match has been identified
Without code, I'm assuming you're writing something like:
for key in dict:
if check_condition(dict[key]):
del dict[key]
If so, you can write
for key in list(dict.keys()):
if key in dict and check_condition(dict[key]):
del dict[key]
list(dict.keys()) returns a copy of the keys, not a view, which makes it possible to delete from the dictionary (you are iterating through a copy of the keys, not the keys in the dictionary itself, in this case.)
Delete all keys whose value is > 15:
for k in mydict.keys(): # makes a list of the keys and iterate
# over the list, not over the dict.
if mydict[k] > 15:
del mydict[k]
Change:
for ansSeries in notmatched:
To:
for ansSeries in notmatched.copy():

Categories