Home > front end >  How to Mix 2 list as Dictionary in Python with custom key value pair
How to Mix 2 list as Dictionary in Python with custom key value pair

Time:02-11

I have 2 List

1. Contains Keys

2. Contains Keys Values

Now I have to make a Dictionary from it which will filter out the keys and insert all the values before the next key arrives in the list.

Example:

List 1: ['a','ef','ddw','b','rf','re','rt','c','dc']
List 2: ['a','b','c']

Dictionary that I want to create: {
'a':['ef','ddw'],
'b':['rf','re','rt'],
'c':['dc']
}
I am only familiar with python language and want solution for same in python only.

CodePudding user response:

I think this should work:

result = {}
cur_key = None
for key in list_1:
    if key in list_2:
        result[key] = []
        cur_key = key
    else:
        result[cur_key].append(key)
  • Related