Python Dictionary

Dictionary is a key: value pair collection in Python. It can contain immutable values like numbers, strings, and tuples as the key. Values can be any data type in Python including another dictionary.

Python Dictionary Properties

  • Keys are unique and immutable.
  • Values can be duplicate and of any data type.
  • Dictionary is mutable.

Dictionary Representation

A dictionary object in Python is denoted by {} and it has values seperated by ,

>>> d = {} # empty dictionary
>>> d = {1: 100, "a":"apple"} >>> type(d) dict

Python Dictionary Attributes

Python dictionary has below built-in functions:

clear()
copy()
fromkeys(iterable, value=None)
get(key, alternate_value)
items()
keys()
pop(key)
popitem()
setdefault(key, value)
update({key:value, ...})
values()

Python Dictionary Comprehension

Dictionary comprehension is a shortcut technique to create a new dictionary object with just one-liner syntax, as below:

{expression for loop if condition}

Common Looping Patterns On A Dictionary Object

    >>> d = {'a':'Apple', 'p':'Programink'}
    >>> for k, v in d.items():
            print(k, v)
    ...
    a Apple
    p Programink

Django training in Bangalore