Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    10
    Rep Power
    0

    Pythonic way to extract variables from dict keys


    The title may be a bit ambiguous, due to it's short nature.

    Ive coded in Python let's say more than once. I come from a Java && PHP background and those are the languages I normally code for a living. I've coded several Python libraries, and every time I must use this wonderful language, I attempt to become a little more Pythonic.

    My questions is:

    If I have a purely example dictionary like so:

    Code:
    leagues = { 'nhl': 'Hockey', 'nfl':'Football', 'mlb':'Baseball', 'mls': 'Soccer' }
    Is there a built-in Pythonic way to extract the keys with their values as individual variables, so that I'd have variables:

    Code:
    nhl = 'Hockey'
    nfl = 'Football'
    etc?

    I currently have my own method that performs this task, but I'm just curious if there is a built-in method that does this.
  2. #2
  3. Contributing User

    Join Date
    Aug 2011
    Posts
    5,285
    Rep Power
    504

    Nasty!


    Code:
    for (key, value) in dictionary.items(): globals()[key] = value
    [edit]code fixed
    and, uh, globals() doesn't seem to be a special dictionary.
    globals()[1]='the' # works, and doesn't change the int 1.[/edit]

    Comments on this post

    • codergeek42 agrees : Hmm...interesting little behavior...
    Last edited by b49P23TIvg; September 15th, 2013 at 08:09 PM. Reason: transcription error corrected
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Brony & F/OSS Advocate
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2003
    Location
    Anaheim, CA (USA)
    Posts
    6,659
    Rep Power
    2477
    Remember that globals is a function, so you can't index or subscript into it directly; but that's the right idea, b49P23TIvg.

    In addition, instead of looping through them, you could just use the dict.update method to put them into the globals. For example:
    python Code:
    leagues = {"nhl": "Hockey", "nfl": "Football"}
    globals().update(leagues)
    print(nhl)
    # outputs "Hockey"
    This comes with the caveat that it will overwrite any variables whose name already exists as a key in the given dictionary.

    Hope that helps.

    Comments on this post

    • b49P23TIvg agrees : Whoops! Typo on my part. update better anyway, so long as we're not checking for valid var names.
    ~~ Peter ~~ :: ( Who am I? ) :: ( Peter's Musings: Uploading myself, bit by bit... ) :: ( Electronic Frontier Foundation ) :: ( I'm a GNU/Linux addict and Free Software Advocate. ) :: ( How to Ask Questions the Smart Way ) :: ( The Fedora Project, sponsored by Red Hat ) :: ( GNOME: The Free Software Desktop Project ) :: ( GnuPG Public Key ) :: ( About me on the WIki )
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    10
    Rep Power
    0
    Gentlemen, thank you very much for your solutions! Thats much better than what I had.
  8. #5
  9. Contributing User

    Join Date
    Aug 2011
    Posts
    5,285
    Rep Power
    504
    I call
    globals[key]=value
    a typo because I did test codes until I got to
    globals()[key]=value
    which was my second try, embarrassing yes, but then retyped into forum instead of cut-and-pasted.
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    39
    Rep Power
    3
    I know this is old, but I feel I should state my method:

    Python Code:
    1.leagues = {"nhl": "Hockey", "nfl": "Football"}
    leagues["nhl"] = value
    leagues["nfl"] = value
    #this also works with a blank dictionary


    though yea, it can't be used as "nhl = value", but it's just as efficient...
    (I think) >.>

    Comments on this post

    • Dietrich agrees : much safer too
  12. #7
  13. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    635
    Rep Power
    66
    Putzing with Python's internal dictionary?
    All in all a dangerous way to code things and not Pythonic!
    Make sure the keys in your dictionary don't hit Python keywords or functions etc.
    This could be a real bitch to debug!
    Last edited by Dietrich; September 20th, 2013 at 11:19 AM.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  14. #8
  15. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    39
    Rep Power
    3
    oh, I just realized...
    I'm not sure how aware you are of this,
    but I forgot to warn:

    Dictionaries may be extremely efficient in performance,
    however their efficiency comes at an extremely high cost of RAM.
    (it's the same in Python as it is in C++, so I've been told)

    that being said, it's much better to store a class, or an array in a dictionary rather than a single value.

    I found this out the hard way... heh
  16. #9
  17. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    635
    Rep Power
    66
    Python dictionaries are extremely optimized, since the language uses them internally too. I wouldn't worry about using dictionaries unless they get gigantic.

    As luck would have it RAM is cheap.
    Last edited by Dietrich; September 20th, 2013 at 06:06 PM.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  18. #10
  19. Contributing User

    Join Date
    Aug 2011
    Posts
    5,285
    Rep Power
    504
    I've used dictionaries with millions of keys, python handled them quite fast, it seemed to me.
    These were mostly faces of 2D finite volumes of a fluent mesh.
    [code]Code tags[/code] are essential for python code and Makefiles!
  20. #11
  21. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    39
    Rep Power
    3
    Originally Posted by b49P23TIvg
    I've used dictionaries with millions of keys, python handled them quite fast, it seemed to me.
    These were mostly faces of 2D finite volumes of a fluent mesh.
    I used it for MineCraft model generation...
    (statues of imported and posed 3D models)

    I couldn't export big models w/o a memory overflow... (2GB RAM)
    now I'm using the array module which is slightly faster than a list and am able to export EXTREMELY large models.

    though I've scrapped the statue plugin recently...
    (restructuring the interface of the main program caused issues in the plugin leading to missing triangles...)


    also... a tip:
    best method for adding data to a list (of indefinate size)
    []+[value]
    it's 3x faster than:
    [].append(value)

    but if the size is known:
    L = [object]*known_size
    for i in range(size): L[i] = object

    Comments on this post

    • Dietrich agrees : thanks for the info
  22. #12
  23. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    39
    Rep Power
    3
    oh I wish I could edit my last post... >.>

    I was corrected on my []+[value] method.
    now I'm finding out [].append(value) actually runs faster...

    I'm not sure if this is a fix with the interpreter,
    or if this is CPU-based performance...
    or even x86 vs x64...

    my original standards were tested on my secondary x86 machine...
    I'll post back when I'm able to test this on my secondary and my backup compys,
    but the append method is definitely faster on both my primary compy and my laptop, which are both x64.
  24. #13
  25. Contributing User

    Join Date
    Aug 2011
    Posts
    5,285
    Rep Power
    504
    Timing code isn't trivial, and with this new devshed interface I've had to refresh the page to get the "edit post" button.
    [code]Code tags[/code] are essential for python code and Makefiles!
  26. #14
  27. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    39
    Rep Power
    3
    Originally Posted by b49P23TIvg
    Timing code isn't trivial, and with this new devshed interface I've had to refresh the page to get the "edit post" button.
    well... I'm one who likes to correct myself after giving bad info and fix it to prevent others from following that bad advice.

    as far as getting the edit post button, I use Dragon (Chrome with security) and refreshing doesn't load one for me :/
  28. #15
  29. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Feb 2001
    Posts
    1,481
    Rep Power
    16
    well... I'm one who likes to correct myself after giving bad info
    I can't think of a reason why the op would ever need to do what they asked, so the correct answer was probably: forget about it. The op's question is a common beginner's question and show's an ignorance of dictionaries--although the op claims to know Java, and Java has dictionary like collections too, and you would never need to do that in Java either.
    Last edited by 7stud; March 25th, 2014 at 01:55 PM.
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo