pythondictionarystring-formattingfield-names

Python: different types of field name in string formatting


Consider the following dictionary:

dic1 = {1:'string', '1': 'int'}

Let's apply string formatting:

print("the value is {0[1]}".format(dic1))
result --> the value is string

but how can I get 'the value is int' as a result?


Solution

  • Should just be this.

    print("the value is {0}".format(dic1['1']))
    

    The {0} only acts as a place holder for text to be put into the string. So an example use would be.

    >>> x=1
    >>> y=2
    >>> z=[3,4,5]
    >>> print "X={0} Y={1} The last element in Z={2}".format(x,y,z[-1])
    X=1 Y=2 The last element in Z=5
    

    You can also do this to change things up. The numbers reference which argument to use from the format command.

    >>> print "X={0} Y={1} The last element in Z={0}".format(x,y,z[-1])
    X=1 Y=2 The last element in Z=1
    

    See now that I changed my string to Z={0} it is actually using the x in the .format(x,y,z[-1]) command.