Home > OS >  Create new dictionary based on user input for values in Python
Create new dictionary based on user input for values in Python

Time:10-25

I have the following dict:

dict_ = {'one':['a','b','c','d'],
'two':['e','f','g'],
'three':['x']}

For the keys that have more than one value, I want to prompt the user to pick one from the list of values and remove the others from the list.

What I have attempted is:

dupl_dict = {}
for k, v in dict_.items():
  if len(v) > 1:
    dupl_dict[k] = v
for k, v in dupl_dict.items():
  user_input = input(f'Choose value for {k} from {v}')
  # code here to drop the values that are not selected by user

The expected output is: if user_input for 'one' is 'b' and if user_input for 'two' is 'f':

new_dict = {'one': 'b', 'two':'f', 'three':'x'}

Note: Maybe this can be accomplished without creating another dict: dupl_dict

CodePudding user response:

Here is my solution to the problem:

  • I use dict_.update() to update the dictionary with the user response.
  • I also check to make sure that they type in a valid response.
dict_ = {'one':['a','b','c','d'],
         'two':['e','f','g'],
         'three':['x']}


for k, v in dict_.items():
    valid_response = False
    if len(v) > 1:
        while not valid_response:
            user_input = input(f'Choose value for {k} from {v}')
            if user_input in v:
                valid_response = True
                dict_.update({k:user_input})
    else:
        dict_.update({k:v[0]})
            
print(dict_)

OUTPUT: when 'b' and 'f' are selected.

{'one': 'b', 'two': 'f', 'three': 'x'}
  • Related