简体   繁体   中英

Take substring from dictionary value

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?

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()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM