Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python nested dictionaries loop

Tags:

python

Is there a better / cleaner / shorter way of getting the same output as the following?

import plistlib
pl = plistlib.readPlist('/Users/username/Documents/wifi1.plist')

n = len(pl)
count = 0
while (count < n):
    print('----------------')
    print(pl[count]['NOISE'])
    print(pl[count]['RSSI'])
    print(pl[count]['SSID_STR'])
    print(pl[count]['BSSID'])
    count += 1

I have tried:

for sub_dict in pl.values():
    print(sub_dict['NOISE'], sub_dict['RSSI'], sub_dict['SSID_STR'], sub_dict['BSSID'])

but I get:

Traceback (most recent call last):
  File "plistread.py", line 17, in <module>
    for sub_dict in pl.values():
AttributeError: 'list' object has no attribute 'values'
like image 395
beoliver Avatar asked Feb 03 '26 04:02

beoliver


1 Answers

You just need:

for sub_dict in pl:

Since pl is a list, iterating through that list will give you each sub dictionary in turn.

A simple example:

>>> l = [1,2,3,4]
>>> for x in l:
...   print x,
... 
1 2 3 4
like image 97
dhg Avatar answered Feb 05 '26 21:02

dhg