Python Dictionary Example

Python dictionary is something like java map. It can hold key value pair values. This example will tell you some basic python dictionary object operations. It includes how to create, add, change and remove python dictionary key and values.

1. Create / Define A Python Dictionary Object.

Python use {  } to define a dictionary object. The key is a string object, the value can be any type.

# create a python dictionary object. 
>>> employee = {'user_name':'tom trump','password':'888888', 'salary': 10000}

# print out above python object value.
>>> employee
{'user_name': 'tom trump', 'password': '888888', 'salary': 10000}

2. Add Key Value Pair In Python Dictionary Object.

You can add a key value pair in python dictionary object with dict_object['key_name'] = value expression.

>>> employee['mobile phone'] = 13912338298
>>> employee
{'user_name': 'tom trump', 'password': '888888', 'salary': 10000, 'mobile phone': 13912338298}

You can also use python dictionary object’s setdefault method to add a new key value pair.

>>> employee.setdefault('sex', 'Male')
'Male'
>>> employee
{'user_name': 'tom trump', 'password': '888888', 'salary': 10000, 'mobile phone': 13912338298, 'sex': 'Male'}

>>> employee.get('sex')
'Male'

3. Get Python Dictionary Value By Key.

Use get method to get python dictionary value by key.

# if key 'age' do not exist, then return empty string.
>>> employee.get('age')

# you can set a default value in the get method second parameter, then if 'age' key do not exist then will return the default value.
>>> employee.get('age', 30)
30

# the 'age' key do not be added in the dictionary object after return default value.
>>> employee
{'user_name': 'tom trump', 'password': '888888', 'salary': 10000, 'mobile phone': 13912338298, 'sex': 'Male'}

4. Delete Python Dictionary Object Key Value Pairs.

Use python del command to delete a key value pair in python dictionary object.

>>> del employee['sex']
>>> employee
{'user_name': 'tom trump', 'password': '888888', 'salary': 10000, 'mobile phone': 13912338298}

5. Update Python Dictionary Value By Key.

To update a key mapped value, just use [ ] to assign new value to it.

>>> employee['password'] = 'hello'
>>> employee
{'user_name': 'tom trump', 'password': 'hello', 'salary': 10000, 'mobile phone': 13912338298}

6. Check Whether Special Key Exist In Dictionary Object Or Not.

Use in operator to check whether dictionary key exist or not.

>>> employee
{'user_name': 'tom trump', 'password': 'hello', 'salary': 10000, 'mobile phone': 13912338298}
>>>
>>> 'user_name' in employee
True
>>> 'sex' in employee
False

7. Loop The Key Value Pair In Python Dictionary Object.

Use python for loop to print out all the key value pairs in python dictionary object.

>>> for key in employee:
...     print(key,' = ',employee[key])
...
user_name  =  tom trump
password  =  hello
salary  =  10000
mobile phone  =  13912338298

8. List Python Dict Object Keys.

# get keys list.
>>> list(employee)
['user_name', 'password', 'salary', 'mobile phone']
>>>
# sort python dictionary object keys list.
>>> sorted(employee)
['mobile phone', 'password', 'salary', 'user_name']

9. Python Dictionary Object keys(), values() and items() Function.

  1. keys() : Get all dict object keys.
    >>> for k in employee.keys():
    ...     print(k)
    ...
    user_name
    password
    salary
    mobile phone
  2. values() : Get all dict object values.
    >>> for v in employee.values():
    ...     print(v)
    ...
    tom trump
    hello
    10000
    13912338298
  3. items() : Get all dict object key value pairs.
    >>> for k,v in employee.items():
    ...     print(k,v)
    ...
    user_name tom trump
    password hello
    salary 10000
    mobile phone 13912338298

10. Python Dict Pop Method.

The pop method will remove the specified key value pair in dict object. It also return the key related value.

>>> employee
{'user_name': 'tom trump', 'password': 'hello', 'salary': 10000, 'mobile phone': 13912338298}
>>>
>>>
>>> employee.pop('salary')
10000
>>> employee
{'user_name': 'tom trump', 'password': 'hello', 'mobile phone': 13912338298}

11. Python Dict Update Method.

The update method will add the Second dict’s key value pairs to the first dict object.

>>> employee
{'user_name': 'tom trump', 'password': 'hello', 'mobile phone': 13912338298}
>>>
>>>
>>> employee_1 = {'hobby':'soccer'}
>>>
>>> employee.update(employee_1)
>>>
>>> employee
{'user_name': 'tom trump', 'password': 'hello', 'mobile phone': 13912338298, 'hobby': 'soccer'}
>>>
>>> employee_1
{'hobby': 'soccer'}
READ :   How To Manage Anaconda Environments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.