-1

I have this dictionary:

{'id': 'centos7', 'remoteVersion': '7.6'}

and this one:

{'id': 'centos7', 'localVersion': '7.5'}

I'd like to get:

{'id': 'centos7', 'remoteVersion': '7.6', 'localVersion': '7.5'}

Is there a pythonic way to do it without having to iterate over all the items?

Chef Tony
  • 435
  • 7
  • 14

1 Answers1

0

Python dictionaries can only have one value per key. You could use a list comprehension to generate a dictionary with values as a list containing the values from your two dictionaries, if you want to avoid writing out an iterator over all the items. An example of a resulting data structure:

{'centos':[{'remoteVersion':'7.6', 'localVersion':'7.5'}]}

That said, I think another solution for you may be using a class:

class myNode:
    def __init__(self, id, remoteVersion, localVersion):
        self.id = id
        self.remoteVersion = remoteVersion
        self.localVersion = localVersion

This allows you to generate myNode objects:

node1 = myNode('centos7', '7.6', '7.5')
jhelphenstine
  • 435
  • 2
  • 10
  • What part of the question makes you assume that this is what OP wants? It is clearly not. – Marco Bonelli Jul 17 '19 at 21:26
  • He's trying to merge dictionaries and preserve the primary key, "id", near as I can tell, so I've offered a way that preserves the unique ID as well as his values. – jhelphenstine Jul 17 '19 at 21:27
  • I'd rather say that he is assuming having two dictionaries with the same `id` key and value, and other different keys. That looks more plausible IMHO. – Marco Bonelli Jul 17 '19 at 21:28
  • I see a primary key of id='centos7', and a dictionary with remoteVersion and one with localVersion. I'd offer a better solution might be a class of nodes defined with members 'id', 'localVersion', and 'remoteVersion', than using dictionaries. Either way, it doesn't look like an attempt to merge dictionaries as referenced with the answer you've linked. – jhelphenstine Jul 17 '19 at 21:31
  • Okay, I can see that the question can be intended both ways, you're right. OP should have made it clearer. – Marco Bonelli Jul 17 '19 at 21:35