通过在排序列表中合并其值来组合两个词典

时间:2015-07-18 03:23:37

标签: python string algorithm dictionary key-value

我在编写函数union_collections时遇到问题,该函数使用两个代表两个书籍集的词典(d1和d2)。该函数生成一个新字典,其中包含d1或d2中存在的所有书籍,同时保持以下规则:

  • 制作的字典不应包含任何重复的书名。
  • 应使用内置的sort()方法对生成的字典中的每个书名列表进行排序。
  • 无法使用解决方案中的keys()内置函数

这些是用于测试的样本集合:

collection1 = \
         {'f':['flatland', 'five minute mysteries', 'films of the 1990s', 'fight club'],
         't':['the art of computer programming', 'the catcher in the rye'],
         'p':['paradise lost', 'professional blackjack', 'paradise regained'],
         'c':['calculus in the real world', 'calculus revisited', 'cooking for one'],
         'd':['dancing with cats', 'disaster at midnight']}

collection2 = \
        {'f':['flatland', 'films of the 1990s'],
         'a':['a brief history of time', 'a tale of two cities'],
         'd':['dealing with stress', 'dancing with cats'],
         't':['the art of computer programming', 'the catcher in the rye'],
         'p':['power and wealth', 'poker essentials', 'post secret'],
         'c':['cat couples', 'calculus', 'calculus revisited',
              'cooking for one', 'calculus in the real world', 'cooking made easy']}`

一个例子:unique_collections(collection1, collection2)应该产生:

{'f' : ['fight club' , 'films of the 1990s', 'five minute mysteries', 'flatland'],
 't' : ['the art of computer programming', 'the catcher in the rye'],
 'p' : ['paradise lost' , 'paradise regained', 'poker essentials', 'post secret' , 'power and wealth', 'professional blackjack'],
 'c' : ['calculus' , 'calculus in the real world' , 'calculus revisited' , 'cat couples', 'cooking for one', 'cooking made easy'],
 'd' : ['dancing with cats' , 'dealing with stress' , 'disaster at midnight'],
 'a' : ['a brief history of time' , 'a tale of two cities']}`

到目前为止,我已写过:

def union_collections(d1, d2):
    union = {}

    for key in d1 or d2:
        if key in d1 and key not in d2: # if the key is only in d1
            union[key] = d1[val]

        if key in d2 and key not in d1: #
            union[key] = d2[val]

        if key in d1 and key in d2:
            union = dict(list(d1.items()) + list(d2.items()))

    return sorted(union.values())

此功能不起作用,我不知道如何修复它以符合以下要求。

无法导入任何模块。

2 个答案:

答案 0 :(得分:3)

def union_collections(d1, d2):
    return { k: sorted(list(set(d1.get(k, []) + d2.get(k, []))))
             for k in set(d1.keys() + d2.keys()) }

与上述相同,但试图更具可读性:

def union_collections(d1, d2):
    return { k: sorted(
                    list(
                        set(
                            d1.get(k, []) + d2.get(k, [])
                        )
                    )
                )
             for k in set(d1.keys() + d2.keys()) }

输出:

{'a': ['a brief history of time', 'a tale of two cities'],
 'c': ['calculus',
       'calculus in the real world',
       'calculus revisited',
       'cat couples',
       'cooking for one',
       'cooking made easy'],
 'd': ['dancing with cats', 'dealing with stress', 'disaster at midnight'],
 'f': ['fight club',
       'films of the 1990s',
       'five minute mysteries',
       'flatland'],
 'p': ['paradise lost',
       'paradise regained',
       'poker essentials',
       'post secret',
       'power and wealth',
       'professional blackjack'],
 't': ['the art of computer programming', 'the catcher in the rye']}

答案 1 :(得分:1)

代码中的一些问题 -

  1. 当你这样做时 - union = dict(list(d1.items()) + list(d2.items())) - 不要认为这是有效的,你不能添加词典。并且不需要,这对您的要求没有意义。

  2. sorted()返回已排序的列表,它不进行就地排序。这只会返回排序的值列表,而不是字典,您需要在直接创建字典时使用list.sort()sorted()函数。

  3. for key in d1 or d2 - 这只会迭代d1中的键,您需要使用set(d1.keys()).union(d2.keys())

  4. d1[val]d2[val]) - 不正确,没有val变量,请改用d1[key]

  5. 对于在两个字典中都找到键的情况,您可以添加两个字典的列表,然后将其转换为set并返回列表,然后对其进行排序,然后将其分配回union字典。示例 -

    def union_collections(d1, d2):
        union = {}
    
        for key in set(d1.keys()).union(d2.keys()):
            if key in d1 and key not in d2: # if the key is only in d1
                union[key] = d1[key]
    
            if key in d2 and key not in d1: 
                union[key] = d2[key]
    
            if key in d1 and key in d2:
                union[key] = sorted(list(set(d1[key] + d2[key])))
    
        return union
    

    正如评论中所说 -

      

    对于两个字典中的密钥,有没有办法在不使用集合的情况下执行此操作?

    没有套装的方法是 -

    def union_collections(d1, d2):
        union = {}
    
        for key in set(d1.keys()).union(d2.keys()):
            if key in d1 and key not in d2: # if the key is only in d1
                union[key] = d1[key]
    
            if key in d2 and key not in d1: 
                union[key] = d2[key]
    
            if key in d1 and key in d2:
                y = []
                union[key] = y
                for x in d1[key]:
                    y.append(x)
                for x in d2[key]:
                    if x not in y:
                        y.append(x)
                y.sort()
    
        return union