python


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. The function produces a new dictionary containing all books present in d1 or d2, while maintaining the following rules:
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.
CANNOT use the built-in function fromkeys() in solution
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:
{'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.
Some issues in your code -
When you do - union = dict(list(d1.items()) + list(d2.items())) - Do not think this is valid, you cannot add dictionaries. And do not need to as well, this does not make sense for your requirement.
sorted() returns the sorted list, it does not do in place sorting. 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.
for key in d1 or d2 - this only iterates over the keys in d1, you need to use set(d1.keys()).union(d2.keys()) .
d1[val] (d2[val]) - is not correct, there is not val variable, use d1[key] instead.
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. 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
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']}

Related Links

'Connection Interrupted' when running simple “Hello World” Python script on Heroku
Encoding - Problems creating JSON using an Unicode Object in Python
Python 2 - Cannot figure out why I am getting invalid literal for int() error message
Filtering models using date range
multiprocessing queue full
Python: How to run nested parallel process in python?
python-requests: Limit Number of Redirects Followed
Python/Bokeh - Plotting Data with Gaps on a Log Scale
Python Getting Level Settings
Variable Explorer freezes when viewing tuples in python Spyder IDE
Is there a way to automate the presentation of pandas Dataframes in an attractive manner
Move Y axis to another position in matplotlib
How to create multiple copies of rows by multiplication in pandas?
Looping to create Python arrays
Get the quotient when dividing a float in Python 2.7
Net Use in Python 3

Categories

HOME
makefile
cil
admin-on-rest
google-cloud-bigtable
answer-set-programming
signalr
system-verilog
raspbian
ocaml
wxwidgets
csvhelper
heap-memory
histogrammar
yocto
bro
docker-windows
codeblocks
internet-explorer-11
gimp
ipfs
vuex
hosts
pjsip
cs-cart
cosmicmind
squarespace
atlassian-plugin-sdk
jive
os161
facebook4j
tcpclient
spring-ws
k2
multichoiceitems
svnkit
geo
recurrence-relation
swagger-editor
es-shell
dql
code-composer
jrules
bing-translator-api
pdftk
ttcn
python-idle
archer
onmouseover
uiviewpropertyanimator
applepayjs
nuget-server
info
static-code-analysis
infinite-scroll
backstop.js
icefaces
c#-interactive
rstudio-server
gradle-eclipse
image-editing
financial
handlebars.java
asymptote
file-diffs
hornetq
application-loader
qbfc
findcontrol
word-2013
multipleselection
start-job
temp-tables
vcl
funkload
ksoap2
flash-cc
json-patch
roxygen
healthvault
robospice
driver-signing
reporting-tools
marmalade-edk
dropdownlistfor
crocodoc
qsqltablemodel
radchart
plone-funnelweb
xmlslurper
law-of-demeter
nintendo
galaxy-tab
windows-live-id
email-spec
gwt-2.2-celltable
act

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App