Files
org_roam/Notes/20250805141906-python_dictionary.org
Zaine e2e4972123
All checks were successful
Build Roam Site / build (push) Successful in 28s
gitea runners
2026-05-06 15:26:35 +01:00

2.7 KiB
Executable File

python-dictionary

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:

  # Create and print a dictionary:
    thisdict =	{
      "brand": "Ford",
      "model": "Mustang",
      "year": 1964
    }
    print(thisdict)

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.

  # create a python dictionary 
  d = {"name": "Geeks", "topic": "dict", "task": "iterate"}

  # loop over dict values
  for val in d.values():
      print(val)

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.

  # 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)

Iterate through both keys and values

You can use the built-in items() method to access both keys and items at the same time. items() method returns the view object that contains the key-value pair as tuples.

  # create a python dictionary 
  d = {"name": "Geeks", "topic": "dict", "task": "iterate"}

  # iterating both key and values
  for key, value in d.items():
      print(f"{key}: {value}")

Sorting:

Lambda function accesses the key (item[0]) during sorting. It offers flexibility if you want to tweak the sorting logic later.

  import operator

  a = {"Gfg": 5, "is": 7, "Best": 2, "for": 9, "geeks": 8}
  res = dict(sorted(a.items(), key=lambda item: item[0]))
  print(res)
{'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9}

Explanation: `lambda item: item[0]` sorts the dictionary by the first element of each tuple (the key).

python-sorted-function

python-lambda