字典中 double .get() 的问题
Problems with double .get() in dictionary
我正在使用嵌套字典,条目如下所示:
net_info = {
'17052242':{'lengthkm': 1.555787, 'uparea': 123.23709555834532, 'order': 2,
'strmDrop_t': 231.5, 'unitarea': 123.23709555834532},
'21009006':{'lengthkm': 6.677901703662528,'uparea': 493.8188826654188,
'order': 2,'strmDrop_t': 5.3, 'unitarea': 36.89608111068623},
.
.
.
}
这是一行代码,我在其中使用 double .get() 在字典中查找键和特征。它就像一个魅力,除非它找不到钥匙......我知道这是因为它将 0 作为钥匙传递给下一个 .get()。我的问题是,如果找不到密钥而不将其传递给下一个 .get(),是否有办法仅 return 0?
unitarea_max = max(net_dictionary.get(in1,0).get('unitarea',0), \
net_dictionary.get(in2,0).get('unitarea',0))
您需要将字典传递给下一个.get()
。由于它是一个空字典,您将从第二个 .get()
.
获得默认值
net_dictionary.get(in1,{}).get('unitarea',0)
您可以使用 NestedDict
。首先安装ndicts
pip install ndicts
然后
from ndicts.ndicts import NestedDict
net_info = {
'17052242': {
'lengthkm': 1.555787,
'uparea': 123.23709555834532,
'order': 2,
'strmDrop_t': 231.5,
'unitarea': 123.23709555834532
},
'21009006': {
'lengthkm': 6.677901703662528,
'uparea': 493.8188826654188,
'order': 2,
'strmDrop_t': 5.3,
'unitarea': 36.89608111068623
}
}
nd = NestedDict(net_info)
zero = nd.get(("wrong key", "unitarea"), 0)
我正在使用嵌套字典,条目如下所示:
net_info = {
'17052242':{'lengthkm': 1.555787, 'uparea': 123.23709555834532, 'order': 2,
'strmDrop_t': 231.5, 'unitarea': 123.23709555834532},
'21009006':{'lengthkm': 6.677901703662528,'uparea': 493.8188826654188,
'order': 2,'strmDrop_t': 5.3, 'unitarea': 36.89608111068623},
.
.
.
}
这是一行代码,我在其中使用 double .get() 在字典中查找键和特征。它就像一个魅力,除非它找不到钥匙......我知道这是因为它将 0 作为钥匙传递给下一个 .get()。我的问题是,如果找不到密钥而不将其传递给下一个 .get(),是否有办法仅 return 0?
unitarea_max = max(net_dictionary.get(in1,0).get('unitarea',0), \
net_dictionary.get(in2,0).get('unitarea',0))
您需要将字典传递给下一个.get()
。由于它是一个空字典,您将从第二个 .get()
.
net_dictionary.get(in1,{}).get('unitarea',0)
您可以使用 NestedDict
。首先安装ndicts
pip install ndicts
然后
from ndicts.ndicts import NestedDict
net_info = {
'17052242': {
'lengthkm': 1.555787,
'uparea': 123.23709555834532,
'order': 2,
'strmDrop_t': 231.5,
'unitarea': 123.23709555834532
},
'21009006': {
'lengthkm': 6.677901703662528,
'uparea': 493.8188826654188,
'order': 2,
'strmDrop_t': 5.3,
'unitarea': 36.89608111068623
}
}
nd = NestedDict(net_info)
zero = nd.get(("wrong key", "unitarea"), 0)