Dictionary problem when key value is taken from a variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Appu2008
    New Member
    • Dec 2007
    • 18

    Dictionary problem when key value is taken from a variable

    Hi,
    I have a dictionary whose keys are variables.
    Eg: - dict=None
    dict[lst]=value
    Here lst and values are 2 variables. How can I make the key
    as the value of lst.
    For eg:- if lst="node1" and if value = 10,
    this is what i needs..

    dict["node1"]=10
    Thanx..
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by Appu2008
    Hi,
    I have a dictionary whose keys are variables.
    Eg: - dict=None
    dict[lst]=value
    Here lst and values are 2 variables. How can I make the key
    as the value of lst.
    For eg:- if lst="node1" and if value = 10,
    this is what i needs..

    dict["node1"]=10
    Thanx..
    Don't use the Python built-in function dict for a variable name. Set your dd to an empty dictionary, not None.[code=Python]>>> dd = {}
    >>> lst = 'Node1'
    >>> value = 10
    >>> dd[lst]=value
    >>> dd
    {'Node1': 10}
    >>> [/code]

    Comment

    • jlm699
      Contributor
      • Jul 2007
      • 314

      #3
      In case you wanted to use some values during the initialization of a dictionary you could do:
      [code=python]
      >>> lst = 'Node1'
      >>> value = 10
      >>> dd = { lst:value }
      >>> dd
      {'Node1': 10}
      >>> [/code]

      Comment

      Working...