Python create variable for each item

▼魔方 西西 提交于 2021-02-08 09:54:40

问题


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.

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.

Code example:

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']

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.


回答1:


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

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




回答2:


# this class simulates cur.fetchall and cur.execute
# to stick with your example code

class Database:
    data = [{"name":"banana","color":"yellow"},{"name":"red_apple","color":"red"}]
    def execute(self,ignored,name):
        for element in self.data :
            if element["name"] == name:
                return element
    def fetchall(self):
        return self.data

cur    = Database()
fruits = cur.fetchall()
mydict = {}
for fruit in fruits :
    fruit_name            = fruit["name"]
    fruit_dict            = cur.execute("SELECT * FROM fruits where name = %s ;",fruit_name)
    mydict[fruit["name"]] = fruit_dict

print "---"
print mydict    
print mydict["red_apple"]
print mydict["banana"]["color"]

trace :

>>> ---
{'red_apple': {'color': 'red', 'name': 'red_apple'}, 'banana': {'color': 'yellow', 'name': 'banana'}}
{'color': 'red', 'name': 'red_apple'}
yellow
>>> 

Suggested reading (and libraries that do just that) :

  • db_row
  • dtuple
  • sqlobject
  • sqlsoup
  • The big list of other relational mappers and sql wrappers


来源:https://stackoverflow.com/questions/21547527/python-create-variable-for-each-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!