Sunday, April 20, 2025

Python Dictionary Operations

We can easily add new key-value pairs:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba["Address"] = "No Name 123"
dba["Tel"] = 555888

print(dba)

Result: 


{'Name': 'Anastasia', 'SSN': 123456, 'Address': 'No Name 123', 'Tel': 555888}
>>> 

Use pop() function to remove specific key-value pair:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba.pop("SSN")

print(dba)

Result:  


{'Name': 'Anastasia'}
>>> 

To remove k-v pair from dictionary end, use popitem() function. Here, we will use it two times:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba.popitem()
dba.popitem()

print(dba)

Result:  


{}
>>> 

To remove all pairs, use clear() function:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba.clear()

print(dba)

Result:  


{}
>>> 

Well known del() function to destroy everything:


dba = {"Name" : "Anastasia", "SSN" : 123456}

del dba

We can take keys and values from keyboard:


dba = {"Name" : "Anastasia", "SSN" : 123456}

k = input("New Key: ")
v = input("New Value: ")

dba[k] = v

print(dba)

Result:  


New Key: Telephone
New Value: 555888
{'Name': 'Anastasia', 'SSN': 123456, 'Telephone': '555888'}
>>> 

Now we know a lot about Python.

It's time to talk about if-else statements - they are just simple checks that we will use all the time in programming.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...