let's say I have the following data frame table:
df
Users Data_Type
User1 String
User2 Integer
User3 String
I have the following sample list which dictionary elements inside it.
my_dicts
[{'name': 'User4', 'dtype': 'StringType'},
{'name': 'User3', 'dtype': 'String'},
{'name': 'User1', 'dtype': 'Boolean'},
{'name': 'User2', 'dtype': 'String'}]
Based on the above table, I would like to update the above existing list of dictionarymy_dicts
. I would like to get the following result.
[{'name': 'User1', 'dtype': 'String'},
{'name': 'User2', 'dtype': 'Integer'},
{'name': 'User3', 'dtype': 'String'}]
I was trying with this:
list_= df['Users'].tolist()
my_new_list= dict(zip((*my_dicts ,), list_))
Can anyone help me with this?
CodePudding user response:
You did not provide how the table is formatted, so I'm assuming this data structure:
updates = [
("User1", "String"),
("User2", "Integer"),
("User3", "String")
]
You can update my_dicts
by going over each element and checking if the name
key corresponds. If so, overwrite dtype
.
for (name, dtype) in updates:
for d in my_dicts:
if d["name"] == name:
d["dtype"] = dtype
I'm not entirely sure what the behavior should be for deleting rows. If any row in my_dict
that is not in the new table should automatically be deleted, then what is the point of updating my_dict
? It sounds like you want to convert the table to your dict datastructure.
CodePudding user response:
newlist = sorted(my_dicts, key=lambda d: d['name'])