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

Pandas: set a default datetime for None values
NLTK can't find the Stanford POS tagger model file
Python __get__ differences between static instance and member
Splitting a 1-d numpy array from tdms file, and plot shorter time series/intervalls from the original array
Why there are more python processes than the number of cores in Spark?
Filling in a completely empty list of lists in an arbitrary order
How to create random orthonormal matrix in python numpy
Fill an image with pre-defined pattern with Wand
How to use a post_save receiver with django-polymorphic?
giving a name to a pandas dataframe?
mistake comparing datetime, python
numpy testing assert array NOT equal
How to join threads of an asyncio executor runned inside coroutine?
Google Admin SDK insert custom schema using python
Importing images for manifold Isomap
Having nosetests watch files from outside container and rerun tests inside container

Categories

HOME
json
visual-studio-2015
crystal-reports
checkbox
jsviews
system-verilog
performancecounter
backup
translation
cpu-architecture
qpython3
actionscript
cartodb
cockroachdb
ssr
data-synchronization
abcpdf
cpanel
squarespace
react-leaflet
scala-native
uisplitviewcontroller
scaling
zope
quartus
rails-activerecord
facebook4j
onsen-ui
spring-ws
bootstrap-typeahead
shopping-cart
python-textprocessing
croppic
katharsis
guile
reactiveui
bitcoin-testnet
dhtmlx-scheduler
ioc-container
strophe
rhomobile
jquery-cycle2
liquid-xml
meta-raspberrypi
installshield-2012
twiki
rule
dart-pub
intellij-idea-2016
exiftool
bayesian-networks
stdclass
service-fabric-stateful
bids
onmouseover
number-theory
ti-basic
slidesjs
etherpad
festival
objloader
sql-server-administration
backstop.js
easing
zurb-foundation-apps
multiple-file-upload
ng2-material
kendo-combobox
clob
spring-lemon
spring-repositories
gemini
amazon-kcl
magento-1.4
selendroid
mogrify
achartengine
google-hadoop
mdm-zinc
ember-cli-addons
ticket-system
jai
omnifocus
microblaze
korma
magic-numbers
initialization-vector
chrome-for-android
jquery-tabs
windows-mobile-6
cdata
html-form-post
localtime
device-emulation
code-conversion
expression-evaluation
ninject-extensions
hibernate3
signals2
point-sprites
ubuntu-11.04
wchar
shared-objects
goliath
ihttphandler
file-encodings

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