简体   繁体   English

通过将两个字典的值合并到排序列表中来合并两个字典

[英]Combining two dictionaries by merging its values in a sorted list

I'm having trouble writing a function union_collections that consumes two dictionaries (d1 and d2) representing two book collections. 我在编写使用两个表示两个书集的字典(d1和d2)的union_collections函数时遇到麻烦。 The function produces a new dictionary containing all books present in d1 or d2, while maintaining the following rules: 该函数将生成一个新字典,其中包含d1或d2中存在的所有书籍,同时保持以下规则:

  • The produced dictionary should not contain any duplicate book titles. 产生的字典不应包含任何重复的书名。
  • Each list of book titles within the produced dictionary should be sorted using the built- in sort() method. 所产生的词典中的书名的每个列表都应使用内置的sort()方法进行排序。
  • CANNOT use the built-in function fromkeys() in solution 解决方案中不能使用内置功能fromkeys()

These are sample collections for testing: 这些是用于测试的样本集合:

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']}`

An example: unique_collections(collection1, collection2) should produce: 例如: 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']}`

So far I've written: 到目前为止,我已经写了:

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())

This function isn't working and I have no idea how to fix it to adhere to the following requirements. 此功能无法正常工作,我不知道如何对其进行修复以符合以下要求。

CANNOT import any modules. 无法导入任何模块。

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

Same as above, but attempting to be more readable: 与上述相同,但尝试更具可读性:

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

Output: 输出:

{'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']}

Some issues in your code - 您的代码中的一些问题-

  1. When you do - union = dict(list(d1.items()) + list(d2.items())) - Do not think this is valid, you cannot add dictionaries. 这样做时union = dict(list(d1.items()) + list(d2.items())) -不要认为这是有效的,就不能添加字典。 And do not need to as well, this does not make sense for your requirement. 并且也不需要,这对您的要求没有意义。

  2. sorted() returns the sorted list, it does not do in place sorting. sorted()返回排序后的列表,它不进行就地排序。 And this would just return the sorted list of values , not the dictionary, you need to use list.sort() or sorted() function when creating the dictionaries directly. 而且这只会返回排序后的值列表,而不是字典,您在直接创建字典时需要使用list.sort()sorted()函数。

  3. for key in d1 or d2 - this only iterates over the keys in d1, you need to use set(d1.keys()).union(d2.keys()) . for key in d1 or d2的键-这仅迭代d1中的键,您需要使用set(d1.keys()).union(d2.keys())

  4. d1[val] ( d2[val] ) - is not correct, there is not val variable, use d1[key] instead. d1[val]d2[val] )-不正确,没有val变量,请改用d1[key]

For the case where a key is found in both dictionary, you can add the lists of both dictionaries and then convert it to set and back to list and then sort it and then assign it back to the union dictionary. 对于在两个字典中都找到键的情况,可以添加两个字典的列表,然后将其转换为set并返回到list,然后对其进行排序,然后将其分配回并union字典。 Example - 范例-

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

As it was asked in the comments - 正如评论中的要求-

for when a key is in both dictionaries, is there a way to do this without the use of sets? 因为当两个字典中都有键时,有没有办法不用集来做到这一点?

The way to do it without sets would be - 没有设置的方式是-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM