【发布时间】:2020-02-23 19:09:21
【问题描述】:
在通过以下代码整理后,我尝试打印 dict 键。效果很好
import pprint
from operator import itemgetter
cars = [
{'Name':'Ka','Year Introduced':1996,'Production of the current model':2014,'Generation':'3rd Generation','Vehicle Information':'Developed by Ford Brazil as a super mini car'},
{'Name':'Fiesta','Year Introduced':1976,'Production of the current model':2017,'Generation':'7th Generation (Mark VIII)','Vehicle Information':'Ford\'s long running subcompact line based on global B-car Platform'},
{'Name':'Focus','Year Introduced':1998,'Production of the current model':2018,'Generation':'3rd Generation (Mark III)','Vehicle Information':'Ford\'s Compact car based on global C-car platform'},
{'Name':'Mondeo','Year Introduced':1992,'Production of the current model':2012,'Generation':'2nd Generation (Fusion)','Vehicle Information':'Mid sized passenger sedan with "One-Ford" design based on CD4 platform.'},
{'Name':'Taurus','Year Introduced':1986,'Production of the current model':2009,'Generation':'6th Generation','Vehicle Information':'Full sized car based on D3 platform'},
{'Name':'Fiesta ST','Year Introduced':2013,'Production of the current model':2013,'Generation':'1st Generation (6th Generation)','Vehicle Information':'Fiesta\'s high performance factory tune'},
{'Name':'Focus RS','Year Introduced':2015,'Production of the current model':2015,'Generation':'1st Generation (3rd Generation)','Vehicle Information':'Special high performance Focus developed by SVT'},
{'Name':'Mustang','Year Introduced':1964,'Production of the current model':2014,'Generation':'6th Generation','Vehicle Information':'Ford\'s long running pony/muscle car'},
{'Name':'GT','Year Introduced':2004,'Production of the current model':2016,'Generation':'2nd Generation','Vehicle Information':'Ford\'s limited production super car inspired by the legendary race car GT40'}
]
# Creates a new dictionary with the name value as the key, and the dictionary as the value
def newDict(carlist):
mynewDict ={}
for car in carlist:
mynewDict[car['Name'],car['Year Introduced']] = car
return mynewDict
def alphaCars(mycardict):
carlist = list(mycardict.keys())
carlist.sort()
#print (carlist)
return carlist
mydict = newDict(cars)
#pprint.pprint (alphaCars(mydict))
for i in sorted (newDict(cars).keys()):
print(i)
我尝试了同样的方法来从 dict 中获取排序后的“值”。尝试了堆栈溢出中提到的单行代码,但我无法这样做。得到下面提到的错误
错误:'dict' 和 'dict' 的实例之间不支持
我从另一个 dict 的实例创建了 dict。我没有使用 lambda,使用 lambda 获得所需的输出很简单。想检查是否可以在没有 lambda 的情况下对 dict 值进行排序。
【问题讨论】:
-
我不确定你的问题是什么,但你只是想这样做
for i in sorted(newDict(cars), key=itemgetter(1)): -
这能回答你的问题吗? How do I sort a dictionary by value?
-
感谢以下语句修复它 "newlist = sorted(alphaCars(mydict), key=itemgetter(1),reverse=True)" 。感谢大家的帮助
标签: python-3.x dictionary key-value-store