0

There are two lists of different lengths. The first contains keys, and the second contains values. Write a function that creates a dictionary from these keys and values. If the key did not have enough values, the dictionary should have the value None. Values that did not have enough keys should be ignored.

a = ['a','b','c']
b = [1,2,3,4,5]

while len(b) < len(a):
  b.append(None)

c = dict(zip(a,b))
print(c)

instead of defining 2 lists in the program, how to solve if user wants input 2 lists of unequal length

2 Answers2

0

Depending on the relative list lengths you will want to use either zip or zip_longest.

Example:

from itertools import zip_longest

keys = ['a','b','c']
values = [1,2, 3, 4, 5]

zip_best = zip if len(values) > len(keys) else zip_longest

c = dict(zip_best(keys, values))

print(c)

Output:

{'a': 1, 'b': 2, 'c': 3}

Edit #1: In response to OP's comment, there are many ways to build lists from user input, but here is one simple way you could construct keys and values lists from user input if you weren't concerned about error handling:

Example:

keys = input("Enter space separated single letter keys: ").split()
values = list(map(int, input("Enter space separated integer values: ").split()))

Edit #2: In response to OP's most recent comment below, zip_longest provides None padding, so in case it wasn't clear, my proposed solution also handles the case where there are more keys than values.

Example:

from itertools import zip_longest

keys = ['a','b','c']
values = [1,2]

zip_best = zip if len(values) > len(keys) else zip_longest

c = dict(zip_best(keys, values))

print(c)

Output:

{'a': 1, 'b': 2, 'c': None}
rhurwitz
  • 2,557
  • 2
  • 10
  • 18
  • keys list and values list have been defined in the code. how do i solve it if user wants to input a key list and value list, and then zip them into a dict – Mohsin Shanavas Mar 19 '21 at 22:16
  • Instead of hard-coding the `keys` and `values` lists as in the example, you could construct those lists from user input using the Python `input` function which prompts the user to enter data then returns that data in string form to the program. Everything else would be the same. – rhurwitz Mar 19 '21 at 22:38
  • thanks. the question also says that if key did not have enough values, the dictionary should have the value none – Mohsin Shanavas Mar 20 '21 at 19:18
  • I believe my solution does that. – rhurwitz Mar 20 '21 at 19:28
0

A direct way to implement this is by specifying that we need to fill values in dict till all keys are covered.

keys = ['a','b','c']
values = [1,2, 3, 4, 5]

res = {keys[i]: values[i] for i in range(len(keys))}

Output:

{'a': 1, 'b': 2, 'c': 3}
Nisarg Bhatt
  • 379
  • 1
  • 13