Friday, November 26, 2021

Several ways of doing same thing in programming - mapping two lists into one dictionary

 In programming there is always more than one way to solve the same problem. This variations depends on individual skills and way of thinking.

In this article I will demonstrate different ways to solve the same problem using python scripting.


The problem:

Python program to map two lists into a dictionary.

countries = ['Nigeria', 'Germany', 'Italy', 'USA', 'Japan', 'Ghana']
score = [39, 23, 12, 67, 45, 11]



The Solution:

1) Using zip() function

# Using zip() function
countries = ['Nigeria', 'Germany', 'Italy', 'USA', 'Japan', 'Ghana']
score = [39, 23, 12, 67, 45, 11]

data = dict(zip(countries, score))
print(data)


2) Using Dictionary Comprehension

# Using Dictionary Comprehension
countries = ['Nigeria', 'Germany', 'Italy', 'USA', 'Japan', 'Ghana']
score = [39, 23, 12, 67, 45, 11]

data  = {key:value for key, value in zip(countries, score)}
print(data)


3) Using For loop

# Using For loop
countries = ['Nigeria', 'Germany', 'Italy', 'USA', 'Japan', 'Ghana']
score = [39, 23, 12, 67, 45, 11]

countries_score = zip(countries, score)

data_dict = {}

for key, value in countries_score:
    if key in data_dict:
        # handling duplicate keys
        pass 
    else:
        data_dict[key] = value
        
print(data_dict)


4) Using For and Range

# Using For and Range
countries = ['Nigeria', 'Germany', 'Italy', 'USA', 'Japan', 'Ghana']
score = [39, 23, 12, 67, 45, 11]

data = {countries[i]: score[i] for i in range(len(countries))}
print(data)


All the four solutions above will give same output result as seen below:-

{'Nigeria': 39, 'Germany': 23, 'Italy': 12, 'USA': 67, 'Japan': 45, 'Ghana': 11}


That is it!

No comments:

Post a Comment