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]}
Related
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.
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}
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()))
If I have an iteration like:
for index in my_dict:
print index.keys()
Is index possible to be a dictionary in this case? If possible, could you please give me an example of what my_dict will look like?
index cannot be a dict as dictionary keys must be hashable types. Since dictionaries are themselves not hashable, they can not serve as keys to another dictionary.
for index in my_dict
iterates over the dictionary keys and will yield the same result as
for index in my_dict.keys()
You can however have a dictionary nested as a value of another dictionary:
{'parent': {'nested': 'some value'}}
# ^ nested dictionary ^
Dictionaries are an unhashable type in Python so another dictionary cannot be used for as a key (or index) to a parent dictionary but it can be used as a value.
That dictionary would look something like this:
my_dict = {'example': {'key': 0}}
And if you wanted to loop over it and select the dictionaries rather than the keys the code would look something like this:
for key in my_dict:
print(my_dict[key].keys())
Which if you've been following along with the example should just output ['key'].
It wasn't part of your question but I'd recommend using a tuple for the kind of data storage and access you want, and if you'd like I can show you how to do that as well.
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]