Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to group a list of tuple by using dictionary in Python

2 Answers

0 votes
lst_tpl = [(1, 30), (6, 50), (7, 30), (2, 50), (0, 50), (3, 20)] 
  
dic = {} 
for x, y in lst_tpl: 
    if y in dic: 
        dic[y].append((x, y)) 
    else: 
        dic[y] = [(x, y)] 
  
print(dic) 


'''
run:

{30: [(1, 30), (7, 30)], 50: [(6, 50), (2, 50), (0, 50)], 20: [(3, 20)]}

'''

 



answered Dec 18, 2019 by avibootz
0 votes
lst_tpl = [(1, 'aa'), (6, 'bb'), (7, 'aa'), (2, 'bb'), (0, 'bb'), (3, 'cc')] 
  
dic = {} 
for x, y in lst_tpl: 
    if y in dic: 
        dic[y].append((x, y)) 
    else: 
        dic[y] = [(x, y)] 
  
print(dic) 


'''
run:

{'aa': [(1, 'aa'), (7, 'aa')], 'bb': [(6, 'bb'), (2, 'bb'), (0, 'bb')], 'cc': [(3, 'cc')]}

'''

 



answered Dec 18, 2019 by avibootz
...