社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python的两个字典中定义交叉引用变量的函数

Tan Sing Chee • 5 年前 • 1325 次点击  

我试图定义一个函数,它允许我指定一个键来交叉引用2个独立的库。一、 我想指定水果名,以及返回成本的函数。

list1 = {"a": "apple", "b" : "banana", "c" : "coconut"}
list2= {"a": 15, "b": 10, "c":5}

def find_fruit_price(fruit, list1, list2):

    for x in list1:
        if fruit in x:
            return list2[x]

    return

find_fruit_price(banana, list1, list2)   # returns a blank output

我在等“10”

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53693
 
1325 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Prune
Reply   •   1 楼
Prune    5 年前
  • banana 是未定义的变量。使用 "banana" 相反。
  • if fruit in x 评估为 if "banana" in "b" ,这将是 False

您需要更改数据逻辑,以便访问和比较可能实际匹配的项。例如

if fruit == list1[x]: