Home > OS >  Take substring from dictionary value
Take substring from dictionary value

Time:03-08

I have a dictionary containing variables and their values.

This is my dictionary, for example:

{27: 'choice = input("Enter choice(1/2/3/4): ")',
 31: 'num1 = float(input("Enter first number: "))',
 32: 'num2 = float(input("Enter second number: "))',
 48: 'next_calculation = input("Let\'s do next calculation? (yes/no): ")'} 

and I want to go over values in the dictionary and save a substring of the string in the list.

The output should look like this from the previous dict:

list = ['choice','num1','num2','next_calculation']

How can I do this?

CodePudding user response:

Use a list comprehension. Assuming d the input dictionary.

lst = [x.split()[0] for x in d.values()]

output: ['choice', 'num1', 'num2', 'next_calculation']

NB. do not name your variable list, this is a python builtin

If you have a very long string or want to explicitly define a different separator, use:

lst = [x.split(sep=' = ', maxsplit=1)[0] for x in d.values()]
  • Related