search a dict keys in python - 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]

Related

Getting keys and values of dictionary if key in list

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.

Creating list from list of dictionaries

I'm tasked with creating a list of the values associated with a specific key from a list of dictionaries.
Currently, I'm two for loops and a conditional into this but I know there's a much more efficient way of going about this.
#lst = list of dict.
#k = specific key being checked for
for dict in lst:
for ind in dict:
if dict[ind] == k:
ret_val.append(dict[ind])
The instructions also state that I am to assume that all dictionaries contain the key and that the value should only be added if the value doesn't already exist.
You might be looking for this:
ret_val = [dict[ind] for dict in lst for ind in dict if dict[ind]==k]

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}

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?
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.
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
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]
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

Identifying keys by looking at values in a dictionary

I have a dictionary with key-value pairs like {a : (b,c,d,e)}.
If i encounter a tuple (b,c,d,e), i want to lookup in dictionary, the key having the same tuple as a value and delete that key from the dictionary. Can it be done like this in python?
use list(),set(), or tuple() because list(dict)or tuple(dict) or set(dict) returns the keys of a dictionary and you can iterate over these returned keys and pop items from the dictionary,
And as Lattyware suggested ,to stop the iteration after removal of one value use break statement after pop().
div={'a':(1,2,3,4),'b':[1,2],'c':(1,2,3,4)}
tup=(1,2,3,4)
for x in set(div):
if div[x]==tup:
div.pop(x)
print(div)
{'b': [1,2]}

Categories