下面是我的字典列表:
我试图从'r_id'删除重复的值。
list_of_dict = [{'fid':200, 'r_id':['4321', '4321']}, {'fid':201, 'r_id':'5321'}]
预期输出
list_of_dict = [{'fid':200, 'r_id':['4321']}, {'fid':201, 'r_id':['5321']}]
我试过下面的代码,但不工作
for item in list_of_dict:
if type(item["record_id"]) == list:
item["record_id"] = [set(item["record_id"])]
请给我建议解决方案
Do:
result = [{ "fid" : d["fid"] , "r_id" : list(set(d["r_id"])) } for d in list_of_dict]
print(result)
或简单的:
for d in list_of_dict:
d["r_id"] = list(set(d["r_id"]))
print(list_of_dict)
如果你真的需要检查类型,使用isinstance:
for d in list_of_dict:
if isinstance(d["r_id"], list):
d["r_id"] = list(set(d["r_id"]))
有关Python中检查类型的规范方法,请阅读此
如果在item['r_id']
中您有另一个类似str
的类型,您可以尝试:
list_of_dict = [{'fid':201, 'r_id':'5321'}, {'fid':200, 'r_id':['4321', '4321']}]
for item in list_of_dict:
if type (item['r_id']) == list:
# if isinstance(item['r_id'],list):
item['r_id'] = list(set(item['r_id']))
elif type (item['r_id']) == str:
# elif isinstance(item['r_id'],str):
item['r_id'] = [item['r_id']]
#Shortest approach
>>> [{'fid' : item['fid'], 'r_id' : list(set(item['r_id'])) if type(item['r_id']) == list else [item['r_id']]} for item in list_of_dict]
[{'fid': 201, 'r_id': ['5321']}, {'fid': 200, 'r_id': ['4321']}]
你就快成功了!虽然可能有其他(更好的)解决方案,但如果您将其更改如下,您的解决方案也将有效:
for item in list_of_dict:
if type(item["r_id"]) == list:
item["r_id"] = list(set(item["r_id"]))
try this:
for items in list_of_dict:
temp_list = list()
if isinstance(item["r_id"], list):
for value in item["r_id"]:
if value not in templist:
temp_list.append(value)
item["r_id"] = temp_list