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,560 questions

51,419 answers

573 users

How to convert 2 lists into a dictionary key-value data structure in Python

1 Answer

0 votes
from collections import defaultdict

# Two lists: one with numeric keys, one with string values
list1 = [5, 3, 1, 9, 48, 21]
list2 = ['bbb', 'ccc', 'tt', 'p', 'qqqq', 'mmm']

# defaultdict(list) automatically creates an empty list for new keys

# defaultdict(list) is a special type of dictionary that 
# automatically creates a default value for any missing key
result_dict = defaultdict(list)

# zip pairs elements: (5, 'bbb'), (3, 'ccc'), ...
for key, value in zip(list1, list2):
    # Append each value to the list associated with its key
    result_dict[key].append(value)

# Convert defaultdict back to a normal dictionary
result_dict = dict(result_dict)

print("dictionary:", result_dict)



'''
run:

dictionary: {5: ['bbb'], 3: ['ccc'], 1: ['tt'], 9: ['p'], 48: ['qqqq'], 21: ['mmm']}

'''

 



answered 1 day ago by avibootz

Related questions

3 answers 198 views
2 answers 251 views
1 answer 147 views
1 answer 112 views
1 answer 149 views
...