Home > Enterprise >  Perform a compare and assign values between two nested-data structures in python using pure python
Perform a compare and assign values between two nested-data structures in python using pure python

Time:03-31

I currently have two datasets (database, assignment) which are nested list-dict and dict-list respectively. I would like to use a sort of vlookup function of a specific key in database, and if the key:value matches a key in assignment, I would like to create a new key-value pair in the original database (sort of assigning someone a task to do, based on their jobscope). I would like to complete this using purely python without importing any libraries (no pandas/numpy etc.)

To explain abit clearer, heres my code and what im trying to achieve:

database = [{‘name’ : ’ABC’, ‘position’ : ‘executive’}, {‘name’ : ’DEF’, ‘position’ : ‘senior exec’}, {‘name’ : ’GEH’, ‘position’ : ‘contractor’}]

assignment = { 'executive': [‘task1', ‘task2’], ‘senior exec’: [‘task3', ‘task4’] , 'contractor': [‘task5']}

Im thinking the code should be follow an if-else logic similar to a vlookup, something like this --

if database[‘position’] == assignment[‘executive’]

create new key – ‘jobscope’ and assign task1, task2 as a list etc.

the output im expecting is something like this:

database = [{‘name’ : ’ABC’, ‘position’ : ‘executive’, ‘jobscope’ : [‘task1', ‘task2’]}, {‘name’ : ’DEF’, ‘position’ : ‘senior exec’, ‘jobscope’ : [‘task3', ‘task4’]}, {‘name’ : ’GEH’, ‘position’ : ‘contractor’, ‘jobscope’ : [‘task5']}]

I’m not sure how to achieve this looping and producing output, also I have some flexibility to change the data structure of assignment so I seek your advice if a dict-list is the best way to achieve this output as well?

CodePudding user response:

This script should work:

database = [
    {'name': 'ABC', 'position': 'executive'},
    {'name': 'DEF', 'position': 'senior exe'},
    {'name': 'GEH', 'position': 'contractor'},
]

assignment = {
    'executive': ['task1', 'task2'],
    'senior exec': ['task3', 'task4'],
    'contractor': ['task5'],
}

for dictionary in database:
    if dictionary['position'] in assignment.keys():
        dictionary['jobscope'] = assignment[dictionary['position']]

print(database)
  • Related