Print ONLY Dictionary Name from Inside a List in Python
我有一个列表,包含三个字典,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | lloyd = { "name":"Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name":"Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name":"Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } students = [lloyd, alice, tyler] |
我想循环浏览列表,只打印字典的名称
即
1 2 3 | lloyd alice tyler |
号
我不想打印字典本身的键或值。
在这方面的任何建议都是有益的。
python中的对象没有"名称",它们被绑定到变量。考虑以下代码:
1 2 | lst1 = [3, [4, 5, 6], 7] lst2 = lst1 |
号
列表的"名称"是什么(可以访问
1 | for i in students:print(i['name']) |
在标准dict类中没有
使用一些附加属性创建一种新类型的dict。
1 2 3 4 5 6 7 8 | class myspecial_dict(dict): def __init__(self,Name,**kwargs): super(myspecial_dict,self).__init__(kwargs) self.dictname=Name mys=myspecial_dict("lloyd",**lloyd) print mys.dictname print mys['quizzes'] |
打印出:
1 2 | lloyd [88.0, 40.0, 94.0] |
。
如果你想为所有人做这件事:
1 2 3 | dicts =[lloyd,alice,tyler] dictnames=["lloyd","alice","tyler"] print [myspecial_dict(x,**y).dictname for x,y in zip(dictnames,dicts) ] |
这就产生了:
1 | ['lloyd', 'alice', 'tyler'] |
。