简体   繁体   中英

Adding a separate string to each item in the list

I have a python list as follows:

new_list = ['emp_salary', 'manager_sal']

I want to change it to below:

['emp_salary' : 'float', 'manager_sal':'float']

I tried something like this:

    >>> users_cols = [l+ ": float" for l in new_list]
   >>> users_cols
       ['emp_salary: float', 'manager_sal: float']

But it is not exactly what i want. The actual list is very big and this is a small example

You can do this to properly define and initialize a dictionary:

new_list = ['emp_salary', 'manager_sal']
users_cols = {}
for key in new_list:
    users_cols[key] = 'float'
new_list = ['emp_salary', 'manager_sal']
new_dict = {key: 'float' for key in new_list}

在清单中,您不需要为此提供字典的东西,它可以存储键值对:

users_col = { key: "float" for key in new_list }

For the sake of completedness:

new_list = ['emp_salary', 'manager_sal']    
new_dict = dict.fromkeys(new_list, "float")

Beware that this will work only if you want to have the same value for each of the keys. Do not use this to declare your mutable values (like sets, lists, dictionaries...), tho unless you want them to all point to the same instance.

You can try this:

new_list = ['emp_salary', 'manager_sal']

final_dict = dict(map(lambda x: (x, "float"), new_list))

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