Python为每个项目创建变量 [英] Python create variable for each item

查看:46
本文介绍了Python为每个项目创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个物品清单.例如 banana apple orange 等.它们每个都有其属性,例如 banana :名称":香蕉",颜色":黄色"

I have a list of items. like banana, apple, orange etc. Each of these has it´s properties, like banana: 'name': 'banana','color': 'yellow' etc.

我想做的是为每个项目创建变量.所以我可以这样称呼它 fruit.banana ['color'] 并返回值 yellow .

What I'm trying to do is create variable's for each item. So i can call it like fruit.banana['color'] and get the value yellow back.

代码示例:

fruits =  cur.fetchall()
for fruittarget in fruits:
    fruit = fruittarget['name']
    cur.execute("SELECT * FROM fruits where name = %s ;",(fruit))
    rows = cur.fetchone()
    name = rows["name"]
    fruitfunc = {name: rows['name']}
    fruitfunc[rows['name']] = {'color': rows['color']}
print fruitfunc[banana]['color']

问题是,每个仅适用于最后一个.如何制作 fruitfunc.banana ['color'] fruitfunc.potato ['color'] ?我想使用 getfruit + name = fruitfunc 这样的变量来设置变量名.因此,为列表中的每个项目创建了一个变量.

Problem is that only works for the very last one in the for each. how do i make a fruitfunc.banana['color'], fruitfunc.potato['color']? I want to set the variable name with a variable like getfruit + name = fruitfunc. So for each item in the list a varible is created.

推荐答案

fruits = {'banana': {'color': 'yellow'}, 'potato': {'color': 'beige'}}

使用名称作为键.要获取香蕉的颜色,请参考 fruits ['banana'] ['color'] .

Use the names as the keys. To get the colour of the banana, refer to fruits['banana']['color'].

这篇关于Python为每个项目创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆