remove duplicates from nested dictionaries in list

前端 未结 6 1888
逝去的感伤
逝去的感伤 2021-02-06 16:13

quick and very basic newbie question.

If i have list of dictionaries looking like this:

L = []
L.append({\"value1\": value1, \"value2\": value2, \"value3         


        
6条回答
  •  梦谈多话
    2021-02-06 17:00

    That's a list of one dictionary and but, assuming there are more dictionaries in the list l:

    l = [ldict for ldict in l if ldict.get("value3") != value3 or ldict.get("value4") != value4]
    

    But is that what you really want to do? Perhaps you need to refine your description.

    BTW, don't use list as a name since it is the name of a Python built-in.

    EDIT: Assuming you started with a list of dictionaries, rather than a list of lists of 1 dictionary each that should work with your example. It wouldn't work if either of the values were None, so better something like:

    l = [ldict for ldict in l if not ( ("value3" in ldict and ldict["value3"] == value3) and ("value4" in ldict and ldict["value4"] == value4) )]
    

    But it still seems like an unusual data structure.

    EDIT: no need to use explicit gets.

    Also, there are always tradeoffs in solutions. Without more info and without actually measuring, it's hard to know which performance tradeoffs are most important for the problem. But, as the Zen sez: "Simple is better than complex".

提交回复
热议问题