Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. List, Tuples and Dictiona...
  5. Dictionaries

Dictionaries

Introduction

  • Dictionary is an unordered collection of key-value pairs
  • When we have the large amount of data, the dictionary data type is used
  • Keys in the dictionary must be unique and be of immutable data type (like strings, numbers or tuples) 
  • Items in dictionary are enclosed in the curly-braces { } and separated by commas (,)
  • A colon (:) is used to separate key from value
  • A key inside the square brackets [ ] is used for accessing the dictionary items
  • Dictionaries are accessed via
    • The keys
    • The values
    • Items (key – value pairs)

Operations

Creating a Dictionary

For creating a dictionary,

Syntax

Dict_var = {key1:value1, key2:value2,…,keyn:valuen}

Example

>>> first_dict = {1:"Apple",2:"Mango",3:"Banana"}
>>> print(first_dict)
{1: 'Apple', 2: 'Mango', 3: 'Banana'}

Accessing the values in Dictionary

Access the items of a dictionary by referring to its key name inside square brackets

Syntax

(Indexing)
Syntax:
Dict_var[key]

Example

>>> print(first_dict[1])
Apple

Adding and Modifying an Item in Dictionary

Change the value of a specific item by referring to its key name

Syntax

Dict_var[key] = value

Example

>>> first_dict[2] = "orange"
>>> print(first_dict)
{1: 'Apple', 2: 'orange', 3: 'Banana'}

Printing keys

Print all key names in the dictionary one by one

Example

>>> print(first_dict.keys())
dict_keys([1, 2, 3])

Printing values

Print all values in the dictionary one by one

Example

>>> print(first_dict.values())
dict_values(['Apple', 'Mango', 'Banana'])

Deleting items in dictionary

del keyword is used to delete

Syntax

del dict_Var[key]

Example

>>> dict1 ={1:"python",2:"English"}
>>> del dict1[2]

To delete the entire dictionary, use the clear( ) function

Syntax

dict_Var.clear()

Example

>>> dict1
{1: 'python'}
>>> dict1.clear()

pop( ) – delete a particular key from the dictionary.

Syntax

dict_Var.pop(key,[default])

Explanation

  • pop( ) method removes an item from the dictionary and returns its value.
  • If the key is not present, then default value is returned.
  •  Default is optional, if default is not specified and key is also not present then it generates key error
>>> dict1
{}
>>> dict1 = {1:"pen", 2:"pencil", 3:"eraser"}
>>> dict1.pop(2,-1)
'pencil'
>>> dict1
{1: 'pen', 3: 'eraser'}

popitem( ) – randomly pops and returns an item from dictionary

Syntax

dict_var.popitem( )

Example

>>> dict1.popitem()
(3, 'eraser')
>>> dict1
{1: 'pen'}

Membership operator

In operator returns true if the key is present. If the key is not present, then it returns false

Syntax

in, not in

Example

>>> dict1 = {1:"pen",2:"pencil", 3:"eraser"}
>>> 1 in dict1
True
>>> 4 not in dict1
True

Copy Dictionary

Returns a shallow copy of the dictionary, i.e., the dictionary returned will not have a duplicate copy of dictionary, but will have the same reference

Syntax

Dict_Var.copy( )

Example

>>> dict1
{1: 'pen', 2: 'pencil', 3: 'eraser'}
>>> dict2 = dict1.copy()
>>> dict2
{1: 'pen', 2: 'pencil', 3: 'eraser'}

Dictionary Length

Returns length of dictionary.

Syntax

len(dict_Var)

Example

>>> dict2
{1: 'pen', 2: 'pencil', 3: 'eraser'}
>>> len(dict2)
3

Dictionary Items

Returns a list of tuples (key – value pairs)

Syntax

dict_Var.items( )

Example

>>> dict2.items()
dict_items([(1, 'pen'), (2, 'pencil'), (3, 'eraser')])

Default Dictionary

Sets a default value for a key that is not present in the dictionary. If the key is already present, then it returns the existing value in the dictionary

Syntax

Dict_var.setdefault(key,value)

Example

>>> dict2.setdefault(4,"Ruler")
'Ruler'
>>> dict2
{1: 'pen', 2: 'pencil', 3: 'eraser', 4: 'Ruler'}
>>> dict2.setdefault(4,"sharpner")
'Ruler'

Update Dictionary

Adds the key value pairs of dict_var1 to dict_var2

Syntax

Dict_var.update(dict_var1)

Example

>>> dict3 = {"total":4, "shop":"AAA industries"}
>>> dict2.update(dict3)
>>> dict2
{1: 'pen', 2: 'pencil', 3: 'eraser', 4: 'Ruler', 'total': 4, 'shop': 'AAA industries'}

From Keys

Creates a new dictionary with keys from sequence and value set to val

Syntax

dict.fromkeys(seq,[val])

Example

>>> Fruits = ["apple", "mango"]
>>> qty = dict.fromkeys(Fruits,4)
>>> qty
{'apple': 4, 'mango': 4}
>>> str1 = "python"
>>> str2 = dict.fromkeys(str1,2)
>>> str2
{'p': 2, 'y': 2, 't': 2, 'h': 2, 'o': 2, 'n': 2}

Dictionary Get

  • Returns the value for the key passed as argument.
  • If the key is not present in dictionary, it will return the default value.
  • If no default value is specified, then it will return none

Syntax

Dict_Var.get(key)

Example

>>> dict2
{1: 'pen', 2: 'pencil', 3: 'eraser', 4: 'Ruler', 'total': 4, 'shop': 'AAA industries'}
>>> dict2.get(2)
'pencil'
>>> dict2.get(5)
>>> dict2.get(5,-1)
-1

Return

  • Returns Boolean value
  • If key is present, then it returns true, else it returns false

Syntax

Dict_var.__contains__(key)

Example

>>> dict1 = {1:20,2:30}
>>> dict1.__contains__(1)
True
>>> dict1.__contains__(5)
False

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments