How can one switch the value and key of a Nested dictionary in Python?

python get nested dictionary keys
python dynamically create nested dictionary
nested dictionary python
python create nested dictionary from list
python get all values from nested dictionary
python find value in nested dictionary
nested dictionary python for loop
python update nested dictionary

I am writing a deferred acceptance algorithm for doctors and hospitals, but before getting there I need my dictionaries to be presented in a correct manner.

Currently, I have a dictionary of doctors containing a nested dictionary with their rankings of hospitals:

{'Doctor_7': {'Hospital_6': 4.0, 'Hospital_3': 8.0, 'Hospital_1': 10.0, 'Hospital_8': 1.0, 'Hospital_2': 9.0, 'Hospital_10': 5.5, 'Hospital_5': 5.5, 'Hospital_7': 2.0, 'Hospital_4': 7.0, 'Hospital_9': 3.0}

Here 'Hospital_6' indicates the hospital and 4.0 indicates its ranking by this specific doctor (4 out of 10 in this case)

Due to the DataFrame from which I made this dictionary it is represented in its current form. However, I want the placement of 'Hospital_6' and 4.0 to switch. Hence, I want 4.0 to be a key and hospital_6 to be its value (of the nested dictionary).

However, I do not quite know how to switch these two. If anyone could help me, that would be extremely appreciated!

You can user dict Comprehension to achieve this:

dict_ ={'Doctor_7': {'Hospital_6': 4.0, 'Hospital_3': 8.0, 'Hospital_1': 10.0, 'Hospital_8': 1.0, 'Hospital_2': 9.0, 'Hospital_10': 5.5, 'Hospital_5': 5.5, 'Hospital_7': 2.0, 'Hospital_4': 7.0, 'Hospital_9': 3.0 }}
new_dict = {key:{v:k for k,v in value.items()} for key, value in dict_.items()}

To learn more about Dict Comprehension: Follow this

NOTE: It will override duplicate keys, which were values in the previous dict. If you have Two hospitals with the same rating, you will get only one.

{'Doctor_7': {4.0: 'Hospital_6',
  8.0: 'Hospital_3',
  10.0: 'Hospital_1',
  1.0: 'Hospital_8',
  9.0: 'Hospital_2',
  5.5: 'Hospital_5',
  2.0: 'Hospital_7',
  7.0: 'Hospital_4',
  3.0: 'Hospital_9'}}

Python Nested Dictionary, How do I convert a list to a dictionary in python? Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let’s discuss various ways of swapping the keys and values in Python Dictionary.

old_dict = {'Doctor_7': {'Hospital_6': 4.0, 'Hospital_3': 8.0, 'Hospital_1': 10.0, 'Hospital_8': 1.0, 'Hospital_2': 9.0, 'Hospital_10': 5.5, 'Hospital_5': 5.5, 'Hospital_7': 2.0, 'Hospital_4': 7.0, 'Hospital_9': 3.0}

new_dict = {doctor: OrderedDict(sorted(((value, hospital) for hospital, value in values.items()), 
            key=lambda p: p[0])) 
            for doctor, values in old_dict.items()}


{'Doctor_7': OrderedDict([(1.0, 'Hospital_8'),
              (2.0, 'Hospital_7'),
              (3.0, 'Hospital_9'),
              (4.0, 'Hospital_6'),
              (5.5, 'Hospital_5'),
              (7.0, 'Hospital_4'),
              (8.0, 'Hospital_3'),
              (9.0, 'Hospital_2'),
              (10.0, 'Hospital_1')])}

Python, dicts, their problems could be solved slightly more easily by using a dict with tuples for keys. You can easily swap the key,dictionary pairs in Python, with a one liner. dict = {value:key for key, value in dict.items()} So in practice you can have something like this:

Since the two solutions so far neglect taking care of duplicate keys (the same rating given to multiple hospitals), here is a solution that does.

It has the disadvantage that every rating points to a list of hospitals with that rating, instead of to the name directly, even if that list has a length of one.

from collections import defaultdict

d = {'Doctor_7': {'Hospital_6': 4.0,
                  'Hospital_3': 8.0,
                  'Hospital_1': 10.0,
                  'Hospital_8': 1.0,
                  'Hospital_2': 9.0,
                  'Hospital_10': 5.5,
                  'Hospital_5': 5.5,
                  'Hospital_7': 2.0,
                  'Hospital_4': 7.0,
                  'Hospital_9': 3.0}}

new_d = {}
for doctor, ratings in d.items():
    ratings_inverse = defaultdict(list)
    for hospital, rating in ratings.items():
    new_d[doctor] = dict(ratings_inverse)

# {'Doctor_7': {1.0: ['Hospital_8'],
#   2.0: ['Hospital_7'],
#   3.0: ['Hospital_9'],
#   4.0: ['Hospital_6'],
#   5.5: ['Hospital_10', 'Hospital_5'],
#   7.0: ['Hospital_4'],
#   8.0: ['Hospital_3'],
#   9.0: ['Hospital_2'],
#   10.0: ['Hospital_1']}}

But since you mention a dataframe, if this is a pandas.DataFrame that looked like this:

#                Doctor_1  Doctor_7
# Hospital_1          1.0      10.0
# Hospital_10         8.0       5.5
# Hospital_2          3.0       9.0
# Hospital_3         10.0       8.0
# Hospital_4          6.0       7.0
# Hospital_5          8.0       5.5
# Hospital_6          4.0       4.0
# Hospital_7          4.0       2.0
# Hospital_8          9.0       1.0
# Hospital_9          3.0       3.0

You can do something like this:

df.apply(lambda col: col.reset_index()\
                        .apply(lambda x: x.tolist()))
#                        Doctor_1                   Doctor_7
# 1.0                [Hospital_1]               [Hospital_8]
# 2.0                         NaN               [Hospital_7]
# 3.0    [Hospital_2, Hospital_9]               [Hospital_9]
# 4.0    [Hospital_6, Hospital_7]               [Hospital_6]
# 5.5                         NaN  [Hospital_10, Hospital_5]
# 6.0                [Hospital_4]                        NaN
# 7.0                         NaN               [Hospital_4]
# 8.0   [Hospital_10, Hospital_5]               [Hospital_3]
# 9.0                [Hospital_8]               [Hospital_2]
# 10.0               [Hospital_3]               [Hospital_1]

Python Convert List to Dictionary, Example 3: How to change or add elements in a When we print the people[3] , we get key:value  Addition of elements to a nested Dictionary can be done in multiple ways. One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.

Is nested dictionary in design ok?, Learn to create a Nested Dictionary in Python, access change add and remove nested You'll often want to create a dictionary with default values for each key. In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. nested_dict = { 'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}} Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two dictionary each having own key and value.

Python Nested Dictionary (With Examples), I have a dictionary whose keys are strings and the values are other, nested dictionaries. The values ( nested dictionaries ) have different  Adding or updating nested dictionary items is easy. Just refer to the item by its key and assign a value. If the key is already present in the dictionary, its value is replaced by the new one. If the key is new, it is added to the dictionary with its value.

How to change value in a nested dictionary?, You can change values within the dictionaries nested within d like this. >>> d['a']['n'] = 10. >>> d['b']['p'] = 23. >>> d. {'a': {'m': 1, 'n': 10}, 'b': {'p': 23, 'q': 86}} You can assign a dictionary value to a variable in Python using the access operator []. For example, Example my_dict = { 'foo': 42, 'bar': 12.5 } new_var = my_dict['foo'] print(new_var) Output. This will give the output − 42. This syntax can also be used to reassign the value associated with this key. For example, Example

  • Hint: dictionary comprehension. Hint 2: ordinary dictionaries cannot be sorted.
  • How do you deal with the fact that a Doctor can give the same rating to multiple hospitals?
  • Duplicate rankings is definitely an issue that I will look into. Preferably hospitals should not be dropped.
  • Thanks for your answer Rajan! I will also look into your link on Dictionary Comprehension. Much appreciated!
  • This silently drops hospitals with the same rating (Hospital_10 and Hospital_5). And which one is kept is not even the same across Python sub-versions.
  • Thank you for your answer FHTMitchell! I will look into the problem of hospitals being dropped.