• Skip to primary navigation
  • Skip to content

Rowell Dionicio

Husband, Father, & Tech Nerd

  • Home
  • About
  • Categories
    • Coding
    • Events
    • Podcasting
    • Professional
    • Wireless
  • Live Stream
  • Contact
  • Show Search
Hide Search

Python Day 4: Dictionaries

September 23, 2018 By Rowell Leave a Comment

Dictionaries

Indexes for dictionaries are called keys. Keys are associated with a value called a key-value pair. A dictionary is unordered. Compared to a List, there is no index starting at 0.

Dictionaries are typed with braces {}. To assign a dictionary to the client1 variable:

client1 = {'rssi': -52, 'channel': 36, 'noise': -96, 'tx rate': 600, 'mcs': 9}

The keys within this dictionary are rssi, channel, noise, tx rate, and mcs. The values for those keys are -52, 36, 96, 600, and 9, respectively.

To access a value through a key it is performed by:

client1[‘channel’]
36

Trying to call a key that doesn’t exist in the dictionary will result in a KeyError error message.

client1['bssid']
Traceback (most recent call last):
File "", line 1, in 
KeyError: 'bssid'

With methods, values can be returned from a dictionary. Let’s say I want to print out the key and value of client1. I’ll use a for-loop to iterate through each of the key-value pairs and print them out using the items() method.

for i in client1.items():
print(i)
('rssi', -52)
('channel', 36)
('noise', -96)
('tx rate', 600)
('mcs', 9)

If we just needed to print out the keys we would use the keys() method. Again, I’ll use the for-loop to iterate through the keys and print them out:

for k in client1.keys():
print(k)
rssi
channel
noise
tx rate
mcs

If we wanted just the values we can do the same for-loop but call the values() method:

for v in client1.values():
print(v)
-52
36
-96
600
9

Share this:

  • Facebook
  • LinkedIn
  • Twitter

Related

Filed Under: Coding Tagged With: dictionaries, python

Reader Interactions

Leave a Reply Cancel reply

Copyright © 2019 · Written by Rowell Dionicio · You're awesome.