Python Access Dictionary Items
Introduction
Accessing items in a Python dictionary is essential for retrieving and using the stored data. Python provides multiple ways to access dictionary elements including direct key access, get() method, and iterating over keys, values, or items. In this tutorial, we explore all these methods with examples.
Python dictionary के items को access करना ज़रूरी है ताकि संग्रहित डेटा को प्राप्त और उपयोग किया जा सके। Python में dictionary elements को access करने के कई तरीके हैं जैसे सीधे key से access करना, get() method का उपयोग, और keys, values, या items के ऊपर iteration करना। इस ट्यूटोरियल में हम इन सभी तरीकों को उदाहरणों के साथ समझेंगे।
Ways to Access Dictionary Items
- Access by Key
- Using
get()Method - Access All Keys with
keys() - Access All Values with
values() - Access Key-Value Pairs with
items() - Looping through Dictionary
- Key द्वारा Access करना
get()method का उपयोगkeys()से सभी Keys Access करनाvalues()से सभी Values Access करनाitems()से Key-Value जोड़े Access करना- डिक्शनरी में लूप लगाना
Example 1: Access by Key
my_dict = {'name': 'Anita', 'age': 25, 'city': 'Mumbai'}
print(my_dict['name'])
Access the value associated with key 'name' using square brackets.
Square brackets का उपयोग कर 'name' key से value access करें।
Output:
Example 2: Access Using get() Method
my_dict = {'name': 'Anita', 'age': 25}
print(my_dict.get('city', 'Not Found'))
Use get() to safely access a key that may not exist, providing a default value.
get() method का उपयोग करें जो key मौजूद न होने पर default value देता है।
Output:
Example 3: Access All Keys Using keys()
my_dict = {'name': 'Anita', 'age': 25, 'city': 'Mumbai'}
print(list(my_dict.keys()))
Retrieve all keys in the dictionary using keys() method.
keys() method से dictionary की सभी keys प्राप्त करें।
Output:
Example 4: Access All Values Using values()
my_dict = {'name': 'Anita', 'age': 25, 'city': 'Mumbai'}
print(list(my_dict.values()))
Retrieve all values using values() method.
values() method से सभी values प्राप्त करें।
Output:
Example 5: Access All Items Using items()
my_dict = {'name': 'Anita', 'age': 25, 'city': 'Mumbai'}
print(list(my_dict.items()))
Get all key-value pairs as tuples using items() method.
items() method से key-value जोड़े टुपल के रूप में प्राप्त करें।
Output:
Example 6: Loop Through Dictionary Keys
my_dict = {'name': 'Anita', 'age': 25}
for key in my_dict:
print(key)
Loop through dictionary keys directly.
डिक्शनरी की keys पर सीधे loop लगाएं।
Output:
age
Example 7: Loop Through Dictionary Values
my_dict = {'name': 'Anita', 'age': 25}
for value in my_dict.values():
print(value)
Loop through all values using values() method.
values() method से सभी values पर loop लगाएं।
Output:
25
Example 8: Loop Through Key-Value Pairs
my_dict = {'name': 'Anita', 'age': 25}
for key, value in my_dict.items():
print(key, '->', value)
Loop through all key-value pairs using items() method.
items() method से key-value जोड़ों पर loop लगाएं।
Output:
age -> 25