I have two dictionaries with similar values, but different keys. I'd like to update the second dictionary db
with the key value of the first dictionary user
.
What would be the optimal way to do that without overcomplicating logic?
For instance, I have the following dictionaries:
user = {'school': ['books', 'pencils', 'sheets', 'notebooks']}
db = {'education': ['books', 'pencils', 'sheets', 'notebooks'],
'actors': ['student', 'teacher', 'principal']}
user['school']
and db['education']
have the same list value. I just want to update the key value in db
with the one found in user
. The way I thought the implementation is the following:
def get_key(my_dict, val):
for key, value in my_dict.items():
if val == value:
return key
return None
res = {}
for key, value in db.items():
if value in user.values():
key_user = get_key(user, value)
if key_user:
res.update({key_user: value})
else:
res.update({key: value})
print(res)
I am implementing this in Python 3.6.6, so as I understand the order of the dictionary entries is kept.
The desired output would be as follows:
{'school': ['books', 'pencils', 'sheets', 'notebooks'],
'actors': ['student', 'teacher', 'principal']}
As you said the order was important I think the easiest way is to re-create the dictionary, not very efficient for larger datasets though.
We can iterate db
to re-create it, the only thing we need to look at is whether to use the key from user
or db
. If the key exists inside user_values
then we can fetch it's index and use that to get key from user_keys
, otherwise we use key
.
user = {'school': ['books', 'pencils', 'sheets', 'notebooks']}
db = {'education': ['books', 'pencils','sheets','notebooks'],
'actors': ['student','teacher','principal']}
user_keys = tuple(user.keys())
user_values = tuple(user.values())
new_db = {user_keys[user_values.index(value)] if value in user_values else key: value for key, value in db.items()}
>>> {'school': ['books', 'pencils', 'sheets', 'notebooks'],
'actors': ['student', 'teacher', 'principal']}