#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2001
    Posts
    266
    Rep Power
    14

    Passing dictionary elements


    I need to be able to pass dictionary elements into a function but it keeps telling me it is not the correct type.

    Code:
    my_function(my_dict['element'])
    Code:
    def my_function(dict_element):
    
    var = "%s" % dict_element
    This does not work. It won't convert the dict_element to a string. Somehow I need to pass those elements into the function. Any suggestions are appreciated.
  2. #2
  3. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    I dont see any reason why this shouldnt work. The only problem i can see would be a KeyError if the element didn't exist within the dictionary. Does the dictionary contain strings or digits. In any case give this a go:

    Code:
    elements = {'one': 'two', 'three': 'four'}
    
    def function(element):
        print element
    
    function(elements['one'])
    This should simply show the element in the console. Maybe you can show us your whole program since i can't see any reason to do 'var = "%s" % element'; if you do want to convert the element to a string and it isnt already then use the str() function instead i.e.

    Code:
    var = str(element)
    Hope this helps,

    Mark.
    programming language development: www.netytan.com Hula

  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2001
    Posts
    266
    Rep Power
    14
    Thanks for the response. Unfortunately the program is at work and I fired off that question right before I left. I'll look it over again and if I can't figure it out repost on Monday.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2001
    Posts
    266
    Rep Power
    14
    Stepped in Monday morning and got it all to work within 10 minutes. I think the problem was that it was 5:45pm on Friday and I wanted to get the hell out of here.

IMN logo majestic logo threadwatch logo seochat tools logo