是否有更好/更清洁/更短的方式获得与以下相同的输出?
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
我试过了:
for sub_dict in pl.values():
print(sub_dict['NOISE'], sub_dict['RSSI'], sub_dict['SSID_STR'], sub_dict['BSSID'])
但我明白了:
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'
答案 0 :(得分:4)
你只需要:
for sub_dict in pl:
由于pl
是一个列表,因此遍历该列表将依次为您提供每个子字典。
一个简单的例子:
>>> l = [1,2,3,4]
>>> for x in l:
... print x,
...
1 2 3 4
答案 1 :(得分:3)
您可以使用&gt;&gt;&gt;进入&lt;&lt;&lt;声明
for sub_dict in pl:
http://docs.python.org/tutorial/controlflow.html#for-statements
答案 2 :(得分:2)
pl是一个列表,而不是字典。
所以,你应该通过以下方式迭代:
for sub_dict in pl:
print(sub_dict['NOISE'], sub_dict['RSSI'], sub_dict['SSID_STR'], sub_dict['BSSID'])
答案 3 :(得分:1)
如果我理解正确:
keys = ['NOISE', 'RSSI' ... rest of keys]
input = [{'NOISE':1, 'RSSI':2 ... rest of data}, {'NOISE':11, 'RSSI':22 ... rest of data} ... rest of data]
data = [[sub_dict[key] for key in keys] for sub_dict in input]