通过条件引用合并 python 字典值



假设我有两个词典,balprices_eth。我想添加一个新的键bal[eth],如果资产与prices_eth中的值匹配,它将包含资产的价格。例如:

bal={
u'POWR': 5.341, 
u'GXS': 1.758285, 
u'NEO': 20.1805
}
price={
u'POWRETH': 0.00161001, 
u'GXSETH': 0.00974900, 
u'NEOETH': 0.09775400
}

然后我想将它们组合在一起,使它们看起来像这样

bal={
u'POWR' : {
"balance" : 5.341, 
"eth price" : 0.0016100
}, 
u'GXS': {
"balance" : 1.758285, 
"eth price" : 0.00974900
}, 
u'NEO': {
"balance" : 20.1805, 
"eth_price" : 0.09775400
}
}

最简单的解决方案是遍历键的交集,并将相应的余额和价格作为新字典中的条目添加。如果您可以保证如果一个键存在于价格平衡中的任何一个中,它将存在于另一个平衡中,则交集不是必需的。由于我不能从您的问题中假设这一点,因此您可以使用键集上的交集操作来生成公共键(setA.intersection(setB)或简单地setA & setB)。

keyset = set(bal) & set(price)

另一个问题是你的密钥不是通用名称 - python字典中的密钥有足够的"ETH"。如果要执行交集检查以仅获取两个词典中存在的项目,则需要使两个词典的键保持一致。最简单的解决方案是复制一个字典,修复不一致。

c_price = dict()
for key in price:
c_price[key.replace("ETH", "")] = price[key]

或者干脆

c_price = { key.replace('ETH', ''): price[key] for key in price.keys() }

现在,使用两个具有公共键的字典,您可以创建一个字典,通过循环访问键集并在新字典上设置值,将每个键的值合并到单独的字典中。

keyset = set(bal) & set(price)
for key in keyset:
combined[key] = {'bal' : bal[key, 'price' : price[key])}

或者干脆

combined = { key : {'bal' : bal[key], 'price' : price[key]} for key in keyset }

您只需将 them 键中的值更改为字典,然后迭代两个字典中的键即可。

bal_keys= list(bal.keys())
price_keys= list(price.keys())
for balKey, priceKey in zip(bal_keys, price_keys):
if bal[balKey] == price[priceKey]:
bal[balKey]= {"balance": bal[balKey], "eth price": price[priceKey]}

最新更新