2017-09-29 57 views
-2
l1 = [{"ID": 1, "Name": "Sagar", "Email": "[email protected]", "Designation": "Software Developer"}, 
     {"ID": 3, "Name": "John", "Email": "[email protected]", "Designation": "Software Tester"}, 
     {"ID": 1, "Name": "Sagar", "Email": "[email protected]", "Designation": "Software Developer"}, 
     {"ID": 1, "Name": "Sagar", "Email": "[email protected]", "Designation": "Software Developer"}, 
     {"ID": 2, "Name": "Devid", "Email": "[email protected]", "Designation": "Data Analyst"}, 
     {"ID": 3, "Name": "john", "Email": "[email protected]", "Designation": "Software Tester"}, 
     {"ID": 5, "Name": "Sandy", "Email": "[email protected]", "Designation": "Software Developer"}, 
     {"ID": 4, "Name": "Jenifer", "Email": "[email protected]", "Designation": "Software Developer"}] 

l2 = [{"ID": 1, "Name": "Sagar", "Email": "[email protected]", "Designation": "Software Developer"}, 
     {"ID": 3, "Name": "John", "Email": "[email protected]", "Designation": "Software Tester"}, 
     {"ID": 1, "Name": "Sagar", "Email": "[email protected]", "Designation": "Software Developer"}, 
     {"ID": 1, "Name": "Sagar", "Email": "[email protected]", "Designation": "Software Developer"}, 
     {"ID": 2, "Name": "Devid", "Email": "[email protected]", "Designation": "Data Analyst"}, 
     {"ID": 3, "Name": "john", "Email": "[email protected]", "Designation": "Software Tester"}, 
     {"ID": 5, "Name": "Sandy", "Email": "[email protected]", "Designation": "Software Developer"}, 
     {"ID": 4, "Name": "Jenifer", "Email": "[email protected]", "Designation": "Software Developer"}] 

我想要結果作爲時間名稱在本字典中重複的名字薩加爾。有什麼想法如何做到這一點?如何計算python中重複字典中的時間名稱數

回答

1
在一行中使用理解

傳遞給collections.Counter

import collections 

print(collections.Counter(x['Name'] for x in l1)["Sagar"]) 

這會爲您列表的所有類型的字典的名字反字典,然後採取計數的特定名稱Sagar

0

使用另一個字典並遍歷列表。

names = {} 
for person in l: 
    name = person["Name"] 
    if name in names: 
     names[name] += 1 
    else: 
     names[name] = 1 
+0

這是一個非常和諧的解決方案離子。 –

+0

當然,這很容易理解 –

1

您可以使用以下代碼:

print sum(1 for element in l1 if element['Name'] == 'Sagar')