首页 > 解决方案 > 在字典Python中搜索值的一部分

问题描述

我正在研究自己的投资组合,并且遇到了一些我似乎无法解决的麻烦,或者在鸭鸭 go 的帮助下。

考虑以下字典:

def single_dict():
function_dict = {'gld': gld, 'btc': crypto_btc, 'etc': crypto_etc, 'neo': crypto_neo,
                 'miota': crypto_miota, 'eos': crypto_eos, 'xrp': crypto_xrp, 'nio': stock_nio,
                 'goldrepublic': gold_republic, 'guldens':guldens, 'maple leafs': maple_leafs}

如您所见,字典中的某些值的名称中包含“crypto”一词。现在我想要做的是以这样一种方式迭代字典,即对于 function_dict python 中的每个值,都将相应的键附加到一个列表中。

这可能吗?

我问的原因是因为我有一个绘图功能,例如所有与加密相关的资产,但我想做到这一点,这样我就不必在购买或购买时一直更改我的加密绘图功能例如,出售一个新的加密货币,而是让它检查 function_dict() 以查看它是否需要添加(基于它的值名称中是否包含“crypto”)到饼图。

提前非常感谢!

标签: pythondictionary

解决方案


function_dict = {'gld': 'gld', 'btc': 'crypto_btc', 'etc': 'crypto_etc', 'neo': 'crypto_neo',
                 'miota': 'crypto_miota', 'eos': 'crypto_eos', 'xrp': 'crypto_xrp', 'nio': 'stock_nio',
                 'goldrepublic': 'gold_republic', 'guldens':'guldens', 'maple leafs': 'maple_leafs'}

ans = [key for key,value in function_dict.items() if 'crypto' in value]

输出crypto(在其值中包含子字符串的所有键):

>> ans
['btc', 'etc', 'neo', 'miota', 'eos', 'xrp']

推荐阅读