Home > OS >  how to check and replace list element in dictionary key using python
how to check and replace list element in dictionary key using python

Time:12-03

I am trying to check if list element are exist in dictionary key then replace list element with dictionary values.

Input Data

list1 : ['Customer_Number', 'First_Name', 'Last_Name']
dict1 : {'Customer_Number': 'A', 'First_Name': 'B', 'Middle_Name': 'C', 'Last_Name': 'D', 'Org_Names': 'E'}

Expected Output

list: ['A', 'B', 'D']

code tried

for ele in list1:
    if ele in dict1.keys():
        list1.append(dict1.values())

    

Error getting

keys: dict_keys(['Customer_Number', 'First_Name', 'Middle_Name', 'Last_Name', 'Org_Names'])
TypeError: unhashable type: 'dict_keys'

CodePudding user response:

You are getting errors because you are trying to use a list as a key of the dictionary, which is not possible as only immutable objects like strings, tuples, and integers can be used as a key in a dictionary. To solve this error, make sure that you only use hashable objects when creating an item in a dictionary.

Now moving towards what you want to implement

list1 = ['Customer_Number', 'First_Name', 'Last_Name']
dict1 = {'Customer_Number': 'A', 'First_Name': 'B', 'Middle_Name': 'C', 'Last_Name': 'D', 'Org_Names': 'E'}
newList = []
for key, value in dict1.items():
if key in list1:
    newList.append(value)
print(newList)

CodePudding user response:

Try this:

list1 = ['Customer_Number', 'First_Name', 'Last_Name']
dict1 = {'Customer_Number': 'A', 'First_Name': 'B', 'Middle_Name': 'C', 'Last_Name': 'D', 'Org_Names': 'E'}

res = [v for k,v in dict1.items() if k in list1]

print(res)

CodePudding user response:

try:

res = list()
for k, v in dict1.items():
    if k in list1:
        res.append(v)

print(res)
  • Related