开发者

How to make single from multiple element?

l =  [{'name': 'abc', 'marks': 50}, {'name': 'abc', 'marks': 50}]

I want to uniqify开发者_开发技巧 the dictionary result.

 result = [{'name': 'abc', 'marks': 50}]


Normally, the easiest way to make a list only have unique elements is to convert it to a set, assuming:

  • The list entries are hashable
  • You don't care about the order of the items

However, a dict isn't hashable so in your case it might be easiest just to this by hand:

>>> l =  [{'name': 'abc', 'marks': 50}, {'name': 'abc', 'marks': 50}]
>>> l2 = []
>>> for d in l:
...     if not d in l2:
...         l2.append(d)
...
>>> l2
[{'name': 'abc', 'marks': 50}]

The code above assumes you want to "uniquify" based on exactly matching dict items. For example, if you have two items with the same name but different marks they will both be added to the list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜