initial
This commit is contained in:
63
20250805141906-python_dictionary.org~
Normal file
63
20250805141906-python_dictionary.org~
Normal file
@@ -0,0 +1,63 @@
|
||||
:PROPERTIES:
|
||||
:ID: 125c81dc-c14f-4b4d-93c6-0a2b157735ac
|
||||
:END:
|
||||
#+title: python-dictionary
|
||||
#+filetags: :python:notes:
|
||||
|
||||
Dictionaries are used to store data values in key:value pairs.
|
||||
|
||||
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
|
||||
|
||||
*As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
|
||||
|
||||
Dictionaries are written with curly brackets, and have keys and values:
|
||||
|
||||
#+begin_src python
|
||||
|
||||
# Create and print a dictionary:
|
||||
thisdict = {
|
||||
"brand": "Ford",
|
||||
"model": "Mustang",
|
||||
"year": 1964
|
||||
}
|
||||
print(thisdict)
|
||||
|
||||
#+end_src
|
||||
|
||||
Iterating:
|
||||
|
||||
Iterate through Value
|
||||
|
||||
To iterate through all values of a dictionary in Python using .values(), you can employ a for loop, accessing each value sequentially. This method allows you to process or display each individual value in the dictionary without explicitly referencing the corresponding keys.
|
||||
|
||||
Example: In this example, we are using the values() method to print all the values present in the dictionary.
|
||||
|
||||
#+begin_src python
|
||||
|
||||
# create a python dictionary
|
||||
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}
|
||||
|
||||
# loop over dict values
|
||||
for val in d.values():
|
||||
|
||||
#+end_src
|
||||
|
||||
Iterate through keys
|
||||
|
||||
In Python, just looping through the dictionary provides you its keys. You can also iterate keys of a dictionary using built-in `.keys()` method.
|
||||
|
||||
#+begin_src python
|
||||
|
||||
# create a python dictionary
|
||||
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}
|
||||
|
||||
# default loooping gives keys
|
||||
for keys in d:
|
||||
print(keys)
|
||||
|
||||
# looping through keys
|
||||
for keys in d.keys():
|
||||
print(keys)
|
||||
|
||||
#+end_src
|
||||
|
||||
Reference in New Issue
Block a user