Invert a dictionary inplace - python

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()))

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.

How to add elements of a list to existing dictionary based on key?

I have an iterator for creating multiple lists. I need to keep adding the generated list to a dictionary dict1 based on the key value k:
some value here = k
for a in jsoncontent:
list1.append(a["Value"])
dict1.setdefault(k, []).append(list1)
Right now I get:
{k:[[10,11],[12,32,6],[7,4]]}
But I need:
{k:[10,11,12,32,6,7,4]}
How do I merge these lists?
It sounds like you want extend versus append. extend inserts the contents of the list at the end of the list, while append insets its argument, a list in this case. See https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types

How to retain an item in python dictionary? [duplicate]

This question already has answers here:
Extract a subset of key-value pairs from dictionary?
(14 answers)
Closed 6 years ago.
I've a dictionary my_dict and a list of tokens my_tok as shown:
my_dict = {'tutor': 3,
'useful': 1,
'weather': 1,
'workshop': 3,
'thankful': 1,
'puppy': 1}
my_tok = ['workshop',
'puppy']
Is it possible to retain in my_dict, only the values present in my_tok rather than popping the rest?
i.e., I need to retain only workshop and puppy.
Thanks in advance!
Just overwrite it like so:
my_dict = {k:v for k, v in my_dict.items() if k in my_tok}
This is a dictionary comprehension that recreates my_dict using only the keys that are present as entries in the my_tok list.
As said in the comments, if the number of elemenst in the my_tok list is small compaired to the dictionary keys, this solution is not the most efficient one. In that case it would be much better to iterate through the my_tok list instead as follows:
my_dict = {k:my_dict.get(k, default=None) for k in my_tok}
which is more or less what the other answers propose. The only difference is the use of .get dictionary method with allows us not to care whether the key is present in the dictionary or not. If it isn't it would be assigned the default value.
Going over the values from the my_tok, and get the results that are within the original dictionary.
my_dict = {i:my_dict[i] for i in my_tok}
Create a new copy
You can simply overwrite the original dictionary:
new_dic = {token:my_dict[key] for key in my_tok if key in my_dict}
Mind however that you construct a new dictionary (perhaps you immediately writ it to my_dict) but this has implications: other references to the dictionary will not reflect this change.
Since the number of tokens (my_tok) are limited, it is probably better to iterate over these tokens and do a contains-check on the dictionary (instead of looping over the tuples in the original dictionary).
Update the original dictionary
Given you want to let the changes reflect in your original dictionary, you can in a second step you can .clear() the original dictionary and .update() it accordingly:
new_dic = {token:my_dict[key] for key in my_tok if key in my_dict}
my_dict.clear()
my_dict.update(new_dic)

How can I iterate over a dict which is indexed by a dict?

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.

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