myd = {"abc":11, "def":8, "ghi":10, "jkl":3, "mno":12,
"pqr":9, "stu":11, "wvxyz":15}
我在这三个问题上需要帮助:
编写一个代码,用于打印项目和值,使得该值在myd中最小。
编写一个代码,用于打印项目和值,使得该值在myd中最大。
制作两个新词典myd1
和myd2
,使myd1
包含值小于等于10的项目,myd2包含其余的词典。
答案 0 :(得分:0)
以下是功能:
def max_dict(_dict):
temp = {y:x for x,y in _dict.iteritems()} #Reverse the dict
return temp[max(_dict.values())] #Return the max using the built-in max function
def min_dict(_dict):
temp = {y:x for x,y in _dict.iteritems()} #Reverse the dict
return temp[min(_dict.values())] #Return the min using the built-in min function
def new_dicts(_dict):
_dict1 = {item:value for item, value in _dict.iteritems() if value <= 10} #Dict comprehension
_dict2 = {item:value for item, value in _dict.iteritems() if value > 10} #Dict comprehension
return _dict1, _dict2
作为:
>>> myd = {"abc":11, "def":8, "ghi":10, "jkl":3, "mno":12,
... "pqr":9, "stu":11, "wvxyz":15}
>>> max_dict(myd)
'wvxyz'
>>> min_dict(myd)
'jkl'
>>> new_dicts(myd)
({'jkl': 3, 'pqr': 9, 'ghi': 10, 'def': 8}, {'wvxyz': 15, 'stu': 11, 'abc': 11, 'mno': 12})
>>>
答案 1 :(得分:0)
这里有一些你可以使用的提示:
>>> myd = {"abc":11, "def":8, "ghi":10, "jkl":3, "mno":12, "pqr":9, "stu":11, "wvxyz":15}
>>> myd_key = myd.keys() # will give you list of keys
>>> myd_key
['jkl', 'stu', 'pqr', 'abc', 'mno', 'wvxyz', 'ghi', 'def']
>>> myd_value = myd.values() # will give you list of values
>>> myd_value
[3, 11, 9, 11, 12, 15, 10, 8]
>>> sorted(myd_value) # sort the list
[3, 8, 9, 10, 11, 11, 12, 15]
>>> myd_key = sorted(myd_key,key = lambda x: myd[x]) #sort the key on value
>>> myd_key
['jkl', 'def', 'pqr', 'ghi', 'stu', 'abc', 'mno', 'wvxyz']
>>> print myd_key[0],myd[myd_key[0]]
jkl 3
>>> print myd_key[-1],myd[myd_key[-1]]
wvxyz 15
尝试自己的最后一次