: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 :results output

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

  # loop over dict values
  for val in d.values():
      print(val)
#+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 :results output

  # 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

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.

#+begin_src python :results output

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

#+end_src

Sorting:

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

#+begin_src python :results output
  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)

#+end_src

#+RESULTS:
: {'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).

[[id:3bbc6099-0187-4bf2-9282-97e5fa443f72][python-sorted-function]]

[[id:9d534e89-7f0b-494c-bff6-7b3be05b85d1][python-lambda]]
