迭代字典键的子集

时间:2016-07-18 15:52:01

标签: python for-loop dictionary

我希望学习如何将字典中的某些键/值传递给for循环中的另一个函数。 "某些" keys都共享相同的初始字符串,并以如下所示的尾随整数递增:

data = {}
data["HMD1"] = [a,b,c]
data["HMD2"] = [d,f,g] #and so on...

在同一个字典中还有其他具有不同名称的键。现在在for循环中我想传递以" HMD"开头的每个键的值。到另一个功能。以下是失败尝试的最小工作示例:

data = {}
data["HMD1"] = [0,2,3]
data["HMD2"] = [5,6,4]
data["not"] = 1237659398
data["HMD3"] = [1,1,1]

def dummyfun(vargin):
    print(vargin)
    return vargin

for f in range(1,2,1):
    out = dummyfun(data[eval(''.join(("HMD",str(f))))])

这是一个糟糕的猜测,当然它返回一个错误,因为eval()试图评估" HMD1"这不是变量,而是数据中的关键。有谁知道如何正确地做到这一点?

2 个答案:

答案 0 :(得分:1)

使用for循环遍历字典并使用if语句检查密钥的有效性:

for key in yourDict: #a for loop for dict iterates through its keys
    if 'HMD' in key: #or you can replace with any other conditional
        #DO WHAT YOU WANT TO DO HERE

这是一个快速工作的例子:

>>> data = {'HMD1': [1,2,3], 'HMD23':'heyo mayo', 'HMNOT2':'if this prints, I did something wrong'}
>>> for key in data:
...     if 'HMD' in key:
...             print data[key]
...
[1, 2, 3]
heyo mayo

通过进一步了解您的需求,您还可以向后看并创建关键字符串并打印这些键指向的值:

#let's say you want to print HMD1, HMD2, HMD4, but not anything else
keylist = [#list of keys that you want]
for key in keylist:
    if key in data:
        print data[key]

再次,一个工作的例子。

>>> data = {'HMD1': [1,2,3], 'HMD3':'heyo mayo, this shouldnt print', 'HMD4':123, 'HMD2':['g', 'h', 'i'], 'HMNOT2':'if this prints, I did something wrong'}
>>> keylist = ['HMD1', 'HMD2', 'HMD4']
>>> for key in keylist:
...     if key in data:
...             print data[key]
...
[1, 2, 3]
['g', 'h', 'i']
123

答案 1 :(得分:1)

您根本不需要 # nginx.conf ... server { listen 80; server_name staging.myapp.com *.staging.myapp.com; return 301 https://$server_name$request_uri; } server { listen 80; server_name sandbox.myapp.com *.sandbox.myapp.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name sandbox.myapp.com *.sandbox.myapp.com; root /root/to/sandbox/app; ... } server { listen 443 default_server ssl; server_name demo.myapp.com *.demo.myapp.com; root /root/to/demo/app; ... } 。您只需要使用 request_host = "#{account.subdomain}.#{request.host}/" 构建字符串,例如

eval
用这个你得到了渴望的结果。但如果密钥不在dict中,那将失败,你可以先检查它,捕获异常或提供一个默认值,以防所需的密钥不在那里

.format