Wednesday, September 4, 2024

PYTHON - DICTIONARY

 Dictionary


A Python dictionary is a data structure that stores key-value pairs. It's similar to a real-world dictionary where you look up a word (the key) to find its definition (the value). Here are some essential functions and operations associated with Python dictionaries:

1. Creating a Dictionary: You can create a dictionary using curly braces `{}` and separating key-value pairs with colons.
For example:
   python
   my_dict = {"key1": value1, "key2": value2}

Dict1 = {"Name":"Bhaskar","Desg":"Domain Lead","Age":34,"City":"Chennai"}
print(Dict1)

my_dict2 = dict(name="Bob", age=25, city="Los Angeles")
print(my_dict2)
   

2. Accessing Values: You can access the value associated with a specific key using square brackets [].
For example:
   python
   value = my_dict["key1"]


EID424 = {"Name":"Bhaskar","Desg":"Domain Lead","City":"Chennai"}
EID425 = {"Name":"Senthil","Desg":"Domain Mem","City":"Chennai"}
EID426 = {"Name":"Venkatesh","Desg":"Domain Manager","City":"Chennai"}
print(EID426)
desg = EID426["Desg"]
print(desg)

for item in EID424.values():
    print(item)

for key in E424.keys(): # iterate through keys
    print(key)
   
for value in E424.values():  # iterate through values
    print(value)
   
for key,value in E424.items():  # iterate through keys value pairs
    print(key,value)  

3. Adding or Updating Key-Value Pairs: You can add new key-value pairs or update existing ones by assigning a value to a new or existing key. For example:
   python
   my_dict["new_key"] = new_value
   

4. Removing Key-Value Pairs: You can remove key-value pairs using the del keyword or the `pop()` method. For example:
   python
   del my_dict["key1"]
   value = my_dict.pop("key2")
   

5. Dictionary Methods:
   - keys(): Returns a view object that displays a list of all the keys in the dictionary.
   - values(): Returns a view object that displays a list of all the values in the dictionary.
   - items(): Returns a view object that displays a list of key-value tuples.
   - get(key): Returns the value associated with the specified key. If the key does not exist, it returns `None` (or a default value if provided).
   - clear(): Removes all key-value pairs from the dictionary.

6. Checking Key Existence: You can check if a key exists in a dictionary using the `in` keyword. For example:
   python
   if "key1" in my_dict:
       # do something
 

7. Dictionary Comprehension: Like list comprehensions, Python supports dictionary comprehensions for creating dictionaries in a compact and efficient manner. For example:
   python
   squares = {x: x*x for x in range(1, 6)}
   

These are just some of the fundamental operations and methods associated with Python dictionaries

No comments:

Post a Comment