Loading...
Loading...
00:00:00

Python Dictionary And It's Functions

A dictionary in Python is an unordered collection of key-value pairs, where each key is unique and can be used to retrieve its corresponding value. Dictionaries are defined using curly braces ({}) and can be initialized in the following way:

Create A Dictionary Using this Syntax :

d = {'key1': 'value1', 'key2': 'value2', ...}

Here are some of the most commonly used methods and operations with dictionaries in Python:

  1. len(d): Returns the number of key-value pairs in the dictionary.

  2. d[key]: Returns the value associated with the key in the dictionary. If the key is not found, it raises a KeyError.

  3. d.get(key, default): Returns the value associated with the key in the dictionary. If the key is not found, it returns the default value.

  4. key in d: Returns True if the key is in the dictionary, and False otherwise.

  5. d.keys(): Returns a view object that displays a list of all the keys in the dictionary.

  6. d.values(): Returns a view object that displays a list of all the values in the dictionary.

  7. d.items(): Returns a view object that displays a list of all the key-value pairs in the dictionary.

  8. d.update(other_dictionary): Adds the key-value pairs from other_dictionary to d. If the same key exists in both dictionaries, the value in d will be updated with the value from other_dictionary.

  9. d.pop(key, default): Removes the key-value pair associated with the key in the dictionary and returns its value. If the key is not found, it returns the default value.

  10. d.clear(): Removes all key-value pairs from the dictionary.

Note: The view objects returned by keys(), values(), and items() methods are dynamic, which means that they reflect any changes made to the dictionary.

Create And Access Dictionary

In this example dictionary is created using curly brackets.

a = {"python":2000, "java":5000, "C++": 3000, "html": 1000}
print(a)      # {'python': 2000, 'java': 5000, 'C++': 3000, 'html': 1000}
print(a["java"])    # 5000
print(a["python"])    # 2000
print(a["C++"])    # 3000

Create Dictionary Using Dict() Function

dict() function is used to create a dictionary. It takes multiples arguments that is shown in the Examples

Syntax

dict() #  empty dictionary
dict(iterable)   # iterable object which has key value pair 
dict(**kwargs)   # key value pair seperated by comma dict(one=1, two=2)  

Example:

# create dictionary using dict() function
b = dict({"rahul":100,  "sonam":200, "arjun":300})
print(b)  # {'rahul': 100, 'sonam': 200, 'arjun': 300}
a = dict()   # empty dictionary
print(a)     # {}
b = dict(python= 220, java= 300,cpp=340)
print(b)    # {'python': 220, 'java': 300, 'cpp': 340}

Dictionary Get() Function

get() function return the value of specified key, if key does not exist it raise keyError .

a = {'python': 220, 'java': 300, 'cpp': 340}
print(a)
print(a.get("python"))  #220

Dictionary Pop() Function

pop() function remove the element from dictionary with specified keys and return or if key does not exist raise keyError. 

a = {'python': 220, 'java': 300, 'cpp': 340}
print(a.pop("python"))  #220
print(a)   # {'java': 300, 'cpp': 340}

Dictionary Popitem() Function

popitem() remove the last key-value pair as tuple from the dictionary .

a = {'python': 220, 'java': 300, 'cpp': 340}
print(a.popitem())    #  ('cpp', 340)
print(a)            # {'python': 220, 'java': 300}

Dictionary Setdefault() Function

setdefault() return the value of specified key if not exist set the value as specified .

a = {'python': 220, 'java': 300, 'cpp': 340}
print(a.setdefault("php"))  # None
print(a)   # {'python': 220, 'java': 300, 'cpp': 340, 'php': None}
# setdefault with key and value
a.setdefault("php",0) 
print(a)   # {'python': 220, 'java': 300, 'cpp': 340, 'php': 0}

Dictionary Update() Function

update() function update the dictionary with specified key-value pair.

a = {'python': 220, 'java': 300, 'cpp': 340}
a.update(php=3450) 
print(a)   # {'python': 220, 'java': 300, 'cpp': 340, 'php': 3450}

Dictionary Items() Function

items() function return the all keys-values as list of tuples.

a = {'python': 220, 'java': 300, 'cpp': 340}
print(a.items())    #  dict_items([('python', 220), ('java', 300), ('cpp', 340)])

Dictionary Keys() Function

keys() function return the all keys from the dictionary as list.

a = {'python': 220, 'java': 300, 'cpp': 340}
print(a.keys())    # dict_keys(['python', 'java', 'cpp'])

Dictionary Values() Function

values() function return the all value of all keys as list.

a = {'python': 220, 'java': 300, 'cpp': 340}
print(a.values())    # dict_values([220, 300, 340])