my_dict=dict()
print(type(my_dict))
my_dict={}
print(type(my_dict))
With key value pairs ( data )
my_dict={1:'Alex',2:'Ronald'}
print(my_dict)
Output
{1: 'Alex', 2: 'Ronald'}
| Method | Description |
| clear() | Delete all elements of the dictionary |
| copy() | Copy and create new dictionary |
| fromkeys() | Creating dictionary using keys |
| get() | Collect the value of the input key |
| items() | View object with key value pair |
| keys() | View object with keys |
| popitem() | remove latest added item as a tuple of key value pair |
| pop() | remove the value of input key |
| setdefault() | Getting or adding key with value |
| update() | Adding or updating key and value |
| values() | View object listing the values |
len()
my_dict={'a':'Alex','b':'Ronald'}
print(len(my_dict))
Output
2
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
print(len(my_dict))
Output
3
Length of elements within the key
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
print(len(my_dict['a']))
Output
2
Displaying elements based on position is not possible as dictionary is unindexed. This will give error message.
my_dict={'a':'Alex','b':'Ronald'}
print(my_dict[0])my_dict={'a':'Alex','b':'Ronald'}
print(my_dict['b'])
Output
Ronald
Using get()
my_dict={'a':'Alex','b':'Ronald'}
print(my_dict.get('a'))
Output
Alex
my_dict={'a':'One','b':'Two','c':'Three'}
x=list(my_dict.values()) # list of values
print(x) # ['One', 'Two', 'Three']
my_dict={'a':'Alex','b':'Ronald'}
for i in my_dict:
print(i)
Output is here
a
b
To display values by using for loop
my_dict={'a':'Alex','b':'Ronald'}
for i in my_dict:
print(my_dict[i])
Output is here
Alex
Ronald
Searching key by if condition check
my_dict={'a':'Alex','b':'Ronald'}
if 'b' in my_dict:
print("Yes, it is there ")
else:
print("No, not there")
Output
Yes, it is there
Searching value by using values()
my_dict={'a':'Alex','b':'Ronald'}
if 'Ronald' in my_dict.values():
print("Yes, it is there ")
else:
print("No, not there")
Output is here
Yes, it is there
my_dict={'a':'Alex','b':'Ronald'}
for i,j in my_dict.items():
if j=='Ronald':
print(i)
Output
b
When we use list as value of a dictionary, we can get other values by using any one element of the list. Here by using matching name we get the connected mark ( integer value inside list ) and the key.
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
# display the mark of the matching name along with id
for i,j in my_dict.items():
if j[0]=='Ronald':
print("Mark:",j[1], ", Key or id :",i)
Output
Mark: 40 , Key or id : b
Searching values for matching element
for i,j in my_dict.items():
if 'Ronn' in j:
print(i,">>",j)
my_dict={'a':'Alex','b':'Ronald'}
my_dict['c']='Ronn'
print(my_dict)
Output is here
{'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn'}
Add item by using update() method
del() and the key
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
del my_dict['b']
print(my_dict)
Output
{'a': 'Alex', 'c': 'Ronn'}
If we don’t mention the key in above code then dictionary will be deleted. This code will generate error message.
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
del my_dict
print(my_dict)name 'my_dict' is not defined
Copying a dictionary by using dict() method
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict1=dict(my_dict)
print(my_dict1)
Output
{'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn'}
We can display all elements
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_keys=my_dict.keys()
for i in my_keys:
print(i)
Output is here
a
b
c
Get maximum or minimum element based on Keys or Values of a dictionary.
my_dict1={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict2={'d':'Rabi','b':'Kami','c':'Loren'}
my_dict1.update(my_dict2)
print(my_dict1)# {'a': 'Alex', 'b': 'Kami', 'c': 'Loren', 'd': 'Rabi'}
my_dict1={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict2={'d':'Rabi','b':'Kami','c':'Loren'}
my_out={**my_dict1,**my_dict2}
print(my_out) # {'a': 'Alex', 'b': 'Kami', 'c': 'Loren', 'd': 'Rabi'}
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
print(my_dict['a'][0]) # Output : Alex
print(my_dict['c'][1]) # Output : 50
print(my_dict['a'][:1])# Output : ['Alex']
print(my_dict['a'][:2])# Output : ['Alex', 30]
We can add more elements like one more list to this dictionary
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
print(my_dict['a'][0]) # Output : Alex
print(my_dict['c'][1]) # Output : 50
my_dict.update({'d':['Ravi',60]})
print(my_dict)
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_tutorial")
query = "SELECT * FROM student LIMIT 0,5"
my_data = list(my_conn.execute(query)) # SQLAlchem engine result set
my_dict = {} # Create an empty dictionary
my_list = [] # Create an empty list
for row in my_data:
my_dict[[row][0][0]] = row # id as key
my_list.append(row[1]) # name as list
print(my_dict)
print(my_list)
# Print the other values for matching Name
for i, j in my_dict.items():
if j[1] == "Arnold":
print(i, j[0], j[1], j[2])
my_str='Welcome to Python'
my_dict={}
for i in my_str:
if i in my_dict:
my_dict[i] = my_dict[i] + 1
else:
my_dict[i] = 1
print(my_dict)
Output
{'W': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 3, 'm': 1, ' ': 2,
't': 2, 'P': 1, 'y': 1, 'h': 1, 'n': 1}
Getting unique elements and counting the occurrence by using get().1,Ravi,20,30,40,120
2,Raju,30,40,50,130
3,Alex,40,50,60,140
4,Ronn,50,60,70,150
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.