python嵌套字典循环
是否有更好/更干净/更短的方法获得与以下相同的输出python嵌套字典循环,python,Python,是否有更好/更干净/更短的方法获得与以下相同的输出 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
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
但我得到:
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'
回溯(最近一次呼叫最后一次):
文件“plistread.py”,第17行,在
对于pl.values()中的子目录:
AttributeError:“列表”对象没有属性“值”
您只需要:
for sub_dict in pl:
由于pl
是一个列表,遍历该列表将依次给出每个子字典
一个简单的例子:
>>> l = [1,2,3,4]
>>> for x in l:
... print x,
...
1 2 3 4
您可以使用>>>,因为inpl是一个列表,而不是字典 因此,您应该通过以下方式迭代pl:
for sub_dict in pl:
print(sub_dict['NOISE'], sub_dict['RSSI'], sub_dict['SSID_STR'], sub_dict['BSSID'])
如果我理解正确:
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]
您是否尝试过pl中的sub_dict:是的,太完美了。为什么我把它称为pl而不是pl()?是因为它不是一个函数吗?正确
pl
是一个列表,不是一个函数,所以它不应该被“调用”。我只是在等待倒计时,这样我就可以接受你的答案了。。。谢谢
for sub_dict in pl:
print(sub_dict['NOISE'], sub_dict['RSSI'], sub_dict['SSID_STR'], sub_dict['BSSID'])
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]