如何从词典列表中的特定键中获取唯一值?

时间:2019-03-17 17:16:05

标签: python

给我一​​个包含字典的列表,我想从字典的first_name键中获取所有唯一值,如何在python中做到这一点?

data = [
{
    "id": 1,
    "first_name": "John"
},
{   "id": 2,
    "first_name": "Mary"
},
{   "id": 3,
    "first_name": "John"
}
]

3 个答案:

答案 0 :(得分:3)

您可以使用set comprehension

    def _rand111(self, a, b):
        global idx
        if idx in range(12):
            idx += 1
            return 1
        else:
            return 2

    def test_mock_randint(self):
        """
        Test mock the behaviour of `random.randint`
        :return:
        """

        with mock.patch('random.randint', self._rand111):
            assert '111111' == rand_six()
            assert '111111' == rand_six()
            assert '222222' == rand_six()

答案 1 :(得分:3)

>>> set(i["first_name"] for i in data)
{'John', 'Mary'}

如果您希望使用list而不是set,可以将其转换为列表:

>>> list(set(i["first_name"] for i in data))
['John', 'Mary']

答案 2 :(得分:0)

您可以将运算符 $sql_cautare = "SELECT * FROM carti WHERE titlu = '$search'"; 映射到列表中的字典:

itemgetter()