Issue
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'
Solution
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)
Answered By - Ashish Kumar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.