2016-11-21 112 views
0

我有一個元組集:創建的元組的兩個列表詞典列表

users = set(("[email protected]","password"),("[email protected]","password")) 

但可以簡化爲一組...和元組的列表:

licences = [("[email protected]","22"),("[email protected]","23"),("[email protected]","12")] 

對於列表的每個條目,用戶名可以用不同的「許可證」值重複。

我需要建立一個字典列表如下:

[{"user":"[email protected]", "licences":["22","23"]},{"user":"[email protected]", "licences":["12"]}] 

什麼我迄今所做的是這樣的:

licenzadiz = [] 
for num,user in enumerate(users): 
    licenzadiz.append({'user': user[0], 'licences': []}) 
    for num2,licence in enumerate(licences): 
     if user[0] == licence[0]: 
      licenzadiz[num]['licences'].append(licence[1]) 

是運作良好。但我想知道是否有更優雅的解決方案來解決我的問題。

+0

請提供樣品輸入輸出中你的榜樣! – schwobaseggl

+0

什麼是utenti和utente? – ozgur

+1

請爲您的元組集和元組列表提供[MCVE],以及給定演示輸入的預期輸出。我們應該能夠將它複製並粘貼到解釋器中,而不會有任何問題。 –

回答

0

你可以幻想與嵌套的默認類型的字典:

from collections import defaultdict 

items = [('A','1'),('A','3'),('A','2'), 
     ('B','0'),('B','4'),('B','-1'), 
     ('C','7'),('C','6'),('C','12')] 

d = defaultdict(lambda: defaultdict(list)) 

for use,lic in items: 
    d[use]['username'] = use #<-- Overwrites each time an already known key is found, but thats ok 
    d[use]['licence'].append(lic) 


#Just for printout 
for use in d: 
    print d[use] 
    print d[use]['username'] 
    print d[use]['licence'] 

輸出:

defaultdict(<type 'list'>, {'username': 'A', 'licence': ['1', '3', '2']}) 
A 
['1', '3', '2'] 
defaultdict(<type 'list'>, {'username': 'C', 'licence': ['7', '6', '12']}) 
C 
['7', '6', '12'] 
defaultdict(<type 'list'>, {'username': 'B', 'licence': ['0', '4', '-1']}) 
B 
['0', '4', '-1'] 
+0

這非常有趣,謝謝! –

0
data = {} 
for num2,(email, license) in enumerate(licenze): 
    data.setdefault(email,[]).append(license) 

print data #dictionary of email:[licenses,..] 
#or 
print data.items() # if you want a list 

我想......我想