简体   繁体   English

字典更新列表:Python

[英]Update list of dictionaries: Python

let's say I have the following data frame table:假设我有以下数据框表:

df df

Users    Data_Type
User1    String
User2    Integer
User3    String   

I have the following sample list which dictionary elements inside it.我有以下示例列表,其中包含其中的字典元素。

my_dicts 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 dictionary my_dicts .根据上表,我想更新上面现有的字典my_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?谁能帮我这个?

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.您可以通过遍历每个元素并检查name键是否对应来更新my_dicts If so, overwrite dtype .如果是这样,请覆盖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 ?如果my_dict中任何不在新表中的行应该被自动删除,那么更新my_dict的意义何在? It sounds like you want to convert the table to your dict datastructure .听起来您想将表转换为您的 dict 数据结构

newlist = sorted(my_dicts, key=lambda d: d['name']) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM