-2

For example:

MyDict = {"dog" : 3, "cat" : 5}

How do I make it like this:

MyDict = {"cow" : 7, "dog" : 3, "cat" : 5}

With minimal code?

blennd
  • 71
  • 6
  • `MyDict["cow"] = 7`? BTW for a plain dict the order of items in not guaranteed... – Serge Ballesta May 11 '20 at 14:32
  • @SergeBallesta It is in CPython 3.7 and above, but the premise of the question (ie why it even matters to OP) is not clear – DeepSpace May 11 '20 at 14:33
  • Does this answer your question? [How can I add new keys to a dictionary?](https://stackoverflow.com/questions/1024847/how-can-i-add-new-keys-to-a-dictionary) – RoadRunner May 11 '20 at 14:34
  • Even though order is technically maintained in dictionaries now, you might be better off using a different data structure that's meant to preserve order. For example, you could have a list of tuples, where each tuple represents a key-value pair: [ ( "cow", 7 ), ( "dog", 3 ), ( "cat", 5 ) ] – Matvei May 11 '20 at 14:42
  • @Matvei That kills O(1) lookup for O(n) iteration – DeepSpace May 11 '20 at 14:48
  • @DeepSpace That's true. You could improve lookup speed by maintaining a separate dictionary to track the indices of the list elements. Ultimately, it depends on how much data will be stored and how often it needs to be accessed or moved. – Matvei May 11 '20 at 14:57

1 Answers1

3

Assuming we're talking Python 3.7+ (so that dictionaries have fixed order), this should do:

MyDict = {"dog" : 3, "cat" : 5}
MyDict = {"cow": 7, **MyDict}
Błotosmętek
  • 12,717
  • 19
  • 29