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']}
CLICK HERE to find out more related problems solutions.