我有字典词典的值,如:蟒蛇查找字典在字典
myDict = {'custom_field1': {'label': 'CNAMEs', 'data': 'bar1 bar2' },
'custom_field2': {'label': 'LocalForward', 'data': '8080:localhost:80' },
'custom_field3': None,
'custom_field4': {'label': 'ProxyCommand', 'data': 'ssh -q [email protected] nc -q0 %h 22' },
'custom_field5': {'label': 'SomeMoreInfos', 'data': 'AboutSomethingElse' },
'created_by': {'username': 'someperson', 'date': 'recently' },
'name': 'hostname'
}
中有我不关心字典许多其他键/值。获取标签为foo的custom_field的数据,然后标签为bar的数据,然后标签更多的数据的数据是一种简单的方法? 因为目前我做这样的:
customItem = []
for field in range(1, 10):
new_field = myDict.get('custom_field%s' % field)
if new_field is not None:
customItem.append(new_field)
for field in customItem:
if field.get('label') == 'foo' and field.get('data') != '':
for part in field.get('data').split():
"""do something for each"""
for field in customItem:
if field.get('label') == 'bar' and field.get('data') != '':
print (field.get('data'))
我的总体目标是为客户创造一个自动化的ssh_config文件,所以用一个字典为主机,它会创建几个ssh_config中的条目,结果应该像这样的:
hostname (from label 'name')
ProxyCommand ssh -q [email protected] nc -q0 %h 22
hostname-fwd (twice, because there was data behind label 'LocalForward')
ProxyCommand ssh -q [email protected] nc -q0 %h 22
LocalForward 8080:localhost:80
bar1 (as found from label 'CNAMEs')
ProxyCommand ssh -q [email protected] nc -q0 %h 22
bar1-fwd (twice, just because there was data behind label 'bar')
ProxyCommand ssh -q [email protected] nc -q0 %h 22
LocalForward 8080:localhost:80
bar2 (same as with bar1)
ProxyCommand ssh -q [email protected] nc -q0 %h 22
bar2-fwd
ProxyCommand ssh -q [email protected] nc -q0 %h 22
LocalForward 8080:localhost:80
编辑我想更具体与我现在的任务,因为只是随机的sampleData不是那么容易理解,不好意思。
您的问题的第二部分是非常不清楚,但似乎是一个单独的问题,从你在第一部分提出的问题。请分别提问每个问题! – taleinat
@Andreas Hubert你的问题的第二部分需要更多的信息来回答。也许你可以尝试将两者结合成一个问题 – Obsidian
如果您试图通过记录中的不同字段对记录进行索引,您可能需要使用适当的关系数据库。对于小数据集,只需使用[sqlite3'模块](https://docs.python.org/3/library/sqlite3.html)就可以工作(而且你甚至不需要真正的磁盘数据库;'sqlite3'通过连接到“”:memory:“'”支持瞬态数据的内存数据库。 – ShadowRanger