简体   繁体   中英

Python 3.6 - Can a variable value be used as part of a key value in a Dict?

I am using Python 3.6

I can use the .format function to insert a variables value as part of a new variables value as per the below:

var_1 = "First_Var"

var_2 = "Second_Var_{}".format(var_1)

print (var_1, var_2)

This, when run, prints:

First_Var Second_Var_First_Var

I would like to be able to insert the value of var_1 and var_2 as values in a dict as per the below code:

var_1 = "First_Var"

var_2 = "Second_Var_{}".format(var_1)

dict_with_inserts = {'First_Var': '{}_inserted', 'Second_Var': '{}_inserted'}.format(var_1, var_2)

print (dict_with_inserts)

When I run the above I get the below error:

AttributeError: 'dict' object has no attribute 'format'

So it seems I cant use the .format function on dicts. Is there an alternative way to do this or is it not possible to insert the value of a variable within a Python dict?

Any examples or help will be much appreciated.

You can do it like this:

var_1 = "First_Var"

var_2 = "Second_Var_{}".format(var_1)

dict_with_inserts = {'First_Var': '{}_inserted'.format(var_1), 
'Second_Var': '{}_inserted'.format(var_2)}

print (dict_with_inserts)

Is this what you're looking for?

var_1 = "First_Var"
var_2 = "Second_Var_{}".format(var_1)

dict_with_inserts = {'First_Var': '{}_inserted'.format(var_1), 'Second_Var': '{}_inserted'.format(var_2)}

print (dict_with_inserts)

the . format function works on strings alone

However this will achieve the same result as what you are trying to do:

var_1 = "First_Var"

var_2 = "Second_Var_{}".format(var_1)

dict_with_inserts = {'First_Var': '{}_inserted'.format(var_1), 'Second_Var': '{}_inserted'.format(var_2)}

print (dict_with_inserts)

In python 3.6, you can also use literal strings (also called f-strings):

var_1 = 'teststring'

mydict = {'first_var': f'{var_1}_inserted'}

print(mydict)
>> {'first_var': 'teststring_inserted'}

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