0

I am attempting to call a value that is defined within a dictionary creation function. The current issue is the calling of i as an input when it is not defined.

Current code:

mass_list=[10.0,15.0,20.0]
def dict_by_masslist(mass_list,input_value):
    dict_created=[]
    for i in mass_list:
        dict_created.append((i,inputvalue))
    dict_created=dict(dict_created)
    return dict_created

pt_dict_pre_names=dict_by_masslist(mass_list,'pt_'+str(int(i))+'_pre')

Goal output:

pt_dict_pre_names = {10.0: 'pt_10_exp', 15.0: 'pt_15_exp', 20.0: 'pt_20_exp'}

This function will be used to not only name things but generate dictionaries of data. When used outside of the function this scripts works as expected.

0

1 Answer 1

4

Just use a dictionary comprehension instead:

 mass_list = [10.0, 15.0, 20.0]
 pt_dict_pre_names = {x: 'pt_{}_exp'.format(int(x)) for x in mass_list}

What happens here: for every number in mass_list we map the number to a string pt_number_exp that is formatted to include the actual number.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.