I am not able to match the dict values with dict keys because for some dict contains two values.
my_dict = {
'Incident':'INC, Incident',
'Minor Enchancement':'Change',
'ServiceRequest':'SR, ServiceRequest'
}
input:
new_list= ['Incident','Inc','SR','Change']
output:
new_list = ['Incident','Incident','Minor Enchancement','Service Request']
i want read the list and match with dictionary . some key contains two values in the dictionary how can we match dict ?
CodePudding user response:
Here is a better organization:
xlate = {
'INC': 'Incident',
'Inc': 'Incident',
'Change': 'Minor Enhancement',
'SR': 'ServiceRequest'
}
words = ['Incident','Inc','SR','Change']
new_list = []
for w in words:
new_list.append( xlate.get(w, w) )
print(new_list)
Output:
['Incident', 'Incident', 'ServiceRequest', 'Minor Enhancement']
Note that I use .get(w,w)
which will pass "not found" entries through unchanged.
CodePudding user response:
You want to invert the keys and values in the original dictionary, and split the values to produce multiple keys:
my_dict = {
'Incident':'INC, Incident, Inc', #note that I added another alias
'Minor Enchancement':'Change',
'ServiceRequest':'SR, ServiceRequest'
}
reversed_dict = {}
for key in my_dict:
items = [x.strip() for x in my_dict[key].split()]
for i in items:
reversed_dict[i] = key
assert reversed_dict['Incident'] == 'Incident'
assert reversed_dict['Inc'] == 'Incident'
Note that there is no 'magic' way to navigate between using Inc
and INC
, so if you want to be able to handle either case you need to include them as options.
CodePudding user response:
To combine the values of a dictionary with a list, you can use a loop to iterate through the list and check if each element is present as a key in the dictionary. If it is, simply add the corresponding value to the new list. If the element is not present as a key, you can add it directly to the new list.
To handle the case where some keys have more than one value in the dictionary, you can use the split method to split the value into a list and check if the element from the original list is present in the list of values. If it is, simply add the corresponding key to the new list.
Here is an example of how this could be done:
my_dict = {
'Incident':'INC, Incident',
'Minor Enchancement':'Change',
'ServiceRequest':'SR, ServiceRequest'
}
new_list= ['Incident','Inc','SR','Change']
result = []
for item in new_list:
found = False
for key, value in my_dict.items():
if item in value.split(', '):
result.append(key)
found = True
break
if not found:
result.append(item)
print(result)
This should print the desired output:
['Incident', 'Inc', 'ServiceRequest', 'Minor Enchancement']
I hope this helps with your problem. =D