对字典中匹配项创建的列表进行排序

时间:2014-06-07 03:00:50

标签: python dictionary

我是python的新手。我有一本字典和一串钥匙。我必须检查字典中是否存在键并返回匹配列表。如果两个或多个键匹配相同,那么该值应首先出现。

到目前为止,我一直打印比赛。我正在寻找关于如何进行排序的想法。

我的代码如下:

def lookupKeyword(string):

    try:
        dict1 = {'title1': 'title1 an title2', 'title2': 'title7 an title2', 'title3': 'title3 an title2', 'title4': 'title4 an title2', 'title5': 'title5 an title2', 'title6': 'title6 an title2', 'title7': 'title7 an title2'}
        string1 = string.split(",")
        i = 0

        bookList = []
        while(i<len(string1)):
          try:
           if string1[i] in dict1:
            #number_of_matches = 0
            temp = string1[i]
            temp1 = dict1[temp]
            bookList.insert(i,temp1)
            #number_of_matches += 1
          except NoResultsError:
            print "NoResultsError-There are no matches for the given query"
          i += 1
        for x in bookList:
          print x

      except:
        print "There seems to be some error in getting the required details2"

lookupKeyword("title3,title2,title1")

现在bookList看起来像

  1. title3 an title2
  2. title7 an title2
  3. title1 an title2
  4. 但是因为我想要字典中的title1和title2匹配&#34; title1 an title2 &#34;先来就是

    1. title1 an title2
    2. title3 an title2
    3. title7 an title2

2 个答案:

答案 0 :(得分:0)

一种可能的方法是计算总数并对它们进行排序,然后过滤0:

def lookupKeyword(dict1, string):
        string1 = string.split(",")
        match = [ v for k, v in dict1.items() if k in string1 ]
        r = sorted((sum(s in v for s in string1), v) for v in match)
        return [ v[1] for v in reversed(r) if v[0] ]

dict1 = {'title1': 'title1 an title2', 'title2': 'title7 an title2', 
        'title3': 'title3 an title2', 'title4': 'title4 an title2', 
        'title5': 'title5 an title2', 'title6': 'title6 an title2', 
        'title7': 'title7 an title2'}

r = lookupKeyword(dict1, "title3,title2,title1")
for t in r: print t

这给出了:

title3 an title2
title1 an title2
title7 an title2

答案 1 :(得分:0)

希望此代码可以帮助您:

def lookup_keyword(string):

    dict1 = {'title1': 'title1 an title2', 'title2': 'title7 an title2',
             'title3': 'title3 an title2', 'title4': 'title4 an title2',
             'title5': 'title5 an title2', 'title6': 'title6 an title2',
             'title7': 'title7 an title2'}

    string_list = string.split(',')

    r = [v for k, v in dict1.items() if k in string_list]

    if not r:
        print("There seems to be some error in getting the required details2")

    else:
        r.sort()

        for x in r:
            print(x)

测试:

>>> lookup_keyword("title3,title2,title1")
title1 an title2
title3 an title2
title7 an title2