Tutorial on Python Dictionary

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

This is a tutorial on Python Dictionary. Here is an example dictionary…

example = {
"first_name": "Hello",
"last_name": "World",
"answer": 42
}

It consists of key value pairs. You can retrieve the value by indexing on the key like this …

print(example["answer"])
# prints 42

But a better way is to use the built-in get() method like this …

print(example.get("first_name"))
# prints "Hello"

The reason is that if you “get” on a key that does not exist, it returns None instead of getting a KeyError.

Also, you can tell “get” to return a default value if the key requested does not exist in the dictionary …

print(example.get("bad_key", "undefined"))
# prints "undefined"

I’m sure you would agree that the above is better than writing the equivalent below…

if "bad_key" in example:
print(example["bad_key"])
else:
print("undefined")

items(), keys(), values() from dictionary

You can retrieve the dictionary items as key-value tuples using items() …

for key, value in example.items():
print(f"{key} is {value}")

# output
# first_name is Hello
# last_name is World
# answer is 42

Or retrieve just the keys …

for key in example.keys():
print(keys)

Or retrieve just the values …

for value in example.values():
print(value)

There are no ordering of items in a dictionary, so they keys and values can come out in any order.

In a dictionary, the keys are strings and are unique. Values can be of any type.

You can delete an item like this…

del example["answer"]

Or delete everything from the dictionary…

example.clear()

Dictionary Comprehension

Dictionary comprehension is a programmatic way of creating a dictionary.

The following will create a new dictionary that has the same items as the original dictionary…

example = {
"first_name": "Hello",
"last_name": "World",
"answer": 42
}

new_example = { key: value for key, value in example.items() }
print(new_example)

The following will create new dictionary that contain only the items whose values are string…

new_example = { key: value for key, value in example.items() if type(value) == str}

The following converts all values to upper case if they are string; otherwise keep existing value…

new_example = { key: (value.upper() if type(value) == str else value) for key, value in example.items()}

Related Posts

Tags

Share This