Saturday, August 1, 2009

Python: working with hash as key, value pair

Share at Facebook

If you want to print your hash as key=value, or want to perform any other operation at your python hash, its simple. I used to do for loop for this kind of stuff.

## your hash
MY_HASH = {"one":1, "two":2, "four":4, "three":3}
## for each key from your hash
for key in MY_HASH:
## print as key value pair
print key,'=',MY_HASH[key]

Its just taking each key out from the hash, and then using key, its retrieve the value associate with that hash.

But if you need to debug the values of your hash, i don't think its necessary to use this kind of looping at python. Just use direct print on your hash. Like below.

print MY_HASH

The print command from python is a bit intelligent then other languages.

No comments: