【发布时间】:2015-10-07 20:40:44
【问题描述】:
我在编写一个函数 union_collections 时遇到问题,该函数使用两个字典(d1 和 d2),代表两个书籍集合。该函数生成一个新字典,其中包含 d1 或 d2 中存在的所有书籍,同时保持以下规则:
- 生成的字典不应包含任何重复的书名。
- 应使用内置的 sort() 方法对生成的字典中的每个书名列表进行排序。
- 解决方案中不能使用内置函数 fromkeys()
这些是用于测试的样本集合:
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())
此功能不起作用,我不知道如何修复它以符合以下要求。
不能导入任何模块。
【问题讨论】:
-
你的输入dict的数据结构是什么?
-
我有点困惑,你能举一个 key : value 在你的字典里的例子吗?
-
您使用的是哪个版本的 Python?字典的
keys、values和items方法返回的值在 Python 2 和 3 之间发生了很大变化,因此假设错误版本的答案可能没有多大帮助。 -
另外,请用函数的示例输入和预期输出更新帖子
-
我添加了一个示例输入和预期的输出,但我在帖子中的代码出现格式错误
标签: python string algorithm dictionary key-value