Python

 

 

 

 

Python - Dictionary

 

Like a Set or List in Python, a Dictionary is a of distict elements. The main difference between a Dictionary and List/Array is that it assigns a specific key for every elements in it. Every elements in a dictionary is specified as {'Key' : Element }.

 

A Python dictionary is a built-in data structure that stores a collection of key-value pairs. Dictionaries are mutable, unordered, and allow for efficient retrieval, insertion, and deletion of elements based on their keys. The keys in a dictionary must be unique and hashable, which means they can be of data types like integers, floats, strings, and tuples (if the tuple contains hashable elements). The values associated with the keys can be of any data type, including other dictionaries or lists.

 

To create a dictionary, you can use curly braces {} and separate the keys and values with colons, while key-value pairs are separated by commas. An empty dictionary can be created using an empty pair of curly braces {} or the dict() constructor.

 

Some of the main features of dictionaries include:

  • Key-value pairs: Dictionaries store data as key-value pairs, allowing for efficient retrieval of values based on their keys.
  • Unordered: The elements in a dictionary have no defined order. However, starting with Python 3.7, the insertion order of key-value pairs is preserved as an implementation detail, and this became a language feature in Python 3.10.
  • Mutable: Dictionaries can be modified after they are created, allowing you to add, remove, or update key-value pairs.
  • Hashable keys: Dictionary keys must be hashable, which means that mutable types like lists and other dictionaries cannot be used as keys.

Python provides various built-in methods and functions to manipulate dictionaries, such as:

  • keys(): Returns a view object displaying a list of all the keys in the dictionary.
  • values(): Returns a view object displaying a list of all the values in the dictionary.
  • items(): Returns a view object displaying a list of all key-value pairs in the dictionary as tuples.
  • get(): Retrieves the value associated with a given key, or a default value if the key is not present.
  • update(): Adds or updates key-value pairs from another dictionary or an iterable of key-value pairs.
  • pop(): Removes and returns the value associated with a given key, or a default value if the key is not present.
  • popitem(): Removes and returns the last inserted key-value pair as a tuple.
  • del: Removes a key-value pair from the dictionary based on its key.
  • clear(): Removes all key-value pairs from the dictionary.
  • len(): Returns the number of key-value pairs in the dictionary.
  • in: Checks if a key is present in the dictionary.
  • copy(): Returns a shallow copy of the dictionary.

 

 

 

Differences among Array, Set, Dictionary

 

Arrays, sets, and dictionaries are all collection data structures in Python, but they have some key differences in terms of their properties and use cases. Here's a summary of their main differences:

 

Arrays:

  • Arrays are a fixed-size, mutable, and ordered collection of elements, typically of the same data type.
  • Elements can be accessed and modified by their index, allowing for fast and efficient random access.
  • Arrays are not a built-in data structure in Python, but can be used through the array module or other libraries like NumPy.
  • Use cases: Arrays are suitable for situations where you need to store and manipulate elements of the same data type, especially when working with large amounts of numerical data or when you need to perform mathematical operations on the data.

 

Sets:

  • Sets are an unordered collection of unique, hashable elements.
  • Sets do not allow duplicate elements and do not support indexing or slicing.
  • Sets are mutable, and elements can be added or removed after the set is created.
  • Sets are a built-in data structure in Python and can be created using the set() constructor or curly braces {}.
  • Use cases: Sets are suitable for situations where you need to store unique elements, perform membership tests, or carry out mathematical set operations such as unions, intersections, and differences.

 

Dictionaries:

  • Dictionaries store key-value pairs in an unordered collection.
  • Keys must be unique and hashable, while values can be of any data type.
  • Dictionaries are mutable, and key-value pairs can be added, removed, or updated after the dictionary is created.
  • Dictionaries are a built-in data structure in Python and can be created using curly braces {} or the dict() constructor.
  • Use cases: Dictionaries are suitable for situations where you need to store and manipulate data based on keys, such as storing configuration settings, counting word frequencies, or implementing caching mechanisms.

 

 

 

Examples

 

Followings are example showing various usages and operation for Dictionary

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

  • Creating a Dictionary: Direct Creation with Numeric Key - Example 1
  • Creating a Dictionary: Direct Creation with String Key - Example 2
  • Accessing a Dictionary : Using a Numeric Key - Example 3
  • Accessing a Dictionary : Using a String Key - Example 4
  • Accessing a Dictionary : Looping through every elements - Example 5
  • Replacing an Element - Example 6
  • Adding an Element : using update() - Example 7
  • Replacing / Adding in single step : update() - Example 8
  • Removing an element - Example 9  

 

< Example 1 >

 

fruits = {1:"Apple",2:"BlueBerry",3:"Banana",4:"SrawBerry"}

print(fruits)

 

Result :----------------------------------

 

{1: 'Apple', 2: 'BlueBerry', 3: 'Banana', 4: 'SrawBerry'}

 

 

 

< Example 2 >

 

Food = {'Fruit':'Apple','Grain':'Rice','Vegetable':'Cabbage'}

print(Food)

 

Result :----------------------------------

 

{'Fruit': 'Apple', 'Grain': 'Rice', 'Vegetable': 'Cabbage'}

 

 

< Example 3 >

 

fruits = {100:"Apple",200:"BlueBerry",300:"Banana",400:"SrawBerry"}

print(fruits[200])

 

Result :----------------------------------

 

BlueBerry

 

 

< Example 4 >

 

Food = {'Fruit':'Apple','Grain':'Rice','Vegetable':'Cabbage'}

print(Food['Vegetable'])

 

Result :----------------------------------

 

Cabbage

 

NOTE : Try print(Food['Cabbage']) and see what you get. It will give you an error since 'Cabbage' is not a Key. it is an element.

 

 

< Example 5 >

 

Food = {'Fruit':'Apple','Grain':'Rice','Vegetable':'Cabbage'}

 

print('================')

for f in Food :

    print(f)

 

print('================')

foods = list(Food.items())

for F in foods :

    print(F)

 

print('================')

k = list(Food.keys())

 

for i in range(0,len(k)) :

    print(Food[k[i]])

 

print('================')

k = list(Food.keys())

 

for ki in k :

    print(ki,',',Food[ki])

 

Result :----------------------------------

 

================   <-- for f in Food :

Fruit

Grain

Vegetable

================   <-- for F in foods :

('Fruit', 'Apple')

('Grain', 'Rice')

('Vegetable', 'Cabbage')

================   <-- for i in range(0,len(k)) :

Apple

Rice

Cabbage

================   <-- for ki in k :

Fruit , Apple

Grain , Rice

Vegetable , Cabbage

 

 

 

< Example 6 >

 

Food = {'Fruit':'Apple','Grain':'Rice','Vegetable':'Cabbage'}

 

print('================')

foods = list(Food.items())

for f in foods :

    print(f)

 

Food['Fruit'] = 'Grape'

 

print('================')

foods = list(Food.items())

for f in foods :

    print(f)

 

 

Result :----------------------------------

 

================  <-- Original Dictionary

('Fruit', 'Apple')

('Grain', 'Rice')

('Vegetable', 'Cabbage')

================  <-- Dictionary After Change

('Fruit', 'Grape')

('Grain', 'Rice')

('Vegetable', 'Cabbage')

 

 

< Example 7 >

 

Food = {'Fruit':'Apple','Grain':'Rice','Vegetable':'Cabbage'}

 

print('================')

foods = list(Food.items())

for f in foods :

    print(f)

 

Food.update({'Noodle':'Pasta'})

 

print('================')

foods = list(Food.items())

for f in foods :

    print(f)

 

Result :----------------------------------

 

================    <-- Original Dictionary

('Fruit', 'Apple')

('Grain', 'Rice')

('Vegetable', 'Cabbage')

================    <-- Dictionary After Change

('Fruit', 'Apple')

('Grain', 'Rice')

('Vegetable', 'Cabbage')

('Noodle', 'Pasta')

 

 

< Example 8 >

 

Food = {'Fruit':'Apple','Grain':'Rice','Vegetable':'Cabbage'}

 

print('================')

foods = list(Food.items())

for f in foods :

    print(f)

 

Food.update({'Fruit':'Grape','Noodle':'Pasta'})

 

print('================')

foods = list(Food.items())

for f in foods :

    print(f)

 

Result :----------------------------------

 

================      <-- Original Dictionary

('Fruit', 'Apple')

('Grain', 'Rice')

('Vegetable', 'Cabbage')

================      <-- Dictionary After Change

('Fruit', 'Grape')    // This is replaced

('Grain', 'Rice')

('Vegetable', 'Cabbage')

('Noodle', 'Pasta')   // This is added

 

 

 

< Example 9 >

 

Food = {'Fruit':'Apple','Grain':'Rice','Vegetable':'Cabbage'}

 

print('================')

foods = list(Food.items())

for f in foods :

    print(f)

 

del Food['Fruit']

 

print('================')

foods = list(Food.items())

for f in foods :

    print(f)

 

 

Result :----------------------------------

 

================        <-- Original Dictionary

('Fruit', 'Apple')

('Grain', 'Rice')

('Vegetable', 'Cabbage')

================        <-- Dictionary After removing an element

('Grain', 'Rice')

('Vegetable', 'Cabbage')

 

 

 

< Example 10 >