How to Add New Keys to a Dictionary

How can I add new keys to a dictionary?

You create a new key/value pair on a dictionary by assigning a value to that key

d = {'key': 'value'}
print(d) # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}

If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.

Python update a key in dict if it doesn't exist

You do not need to call d.keys(), so

if key not in d:
d[key] = value

is enough. There is no clearer, more readable method.

You could update again with dict.get(), which would return an existing value if the key is already present:

d[key] = d.get(key, value)

but I strongly recommend against this; this is code golfing, hindering maintenance and readability.

Add a new key in the dictionary?

You need to define the type of dic

  • Use any
var dic: any = {}
  • Be more precise
var dic: Record<string, string> = {}
  • Be even more precise
type Key = 'key1' | 'key2' | 'key3' | 'key4'
var keys: Key[] = ['key1', 'key2', 'key3', 'key4']
var dic: Partial<<Record<Key, string>> = {}
  • If the keys are static, then you can make it even better (credit to this thread)
const keys = ['key1', 'key2', 'key3', 'key4'] as const; // TS3.4 syntax
type Key = typeof keys[number];
var dic: Partial<Record<Key, string>> = {
"key1": "123"
}

How to add new values to existing dictionary in python

You should be using a list to store these values. There's no reason to have nested dicts here. Especially since you're just using append here.

Your data would then look like this:

data = {
"key1":["value1-1", "value1-2","value1-3"],
"Key2":["value2-1","value2-2", "value2-3"]}

Then you won't need an if statement just use dict.setdefault

data.setdefault(key, []).append(message)

Add a new item to a dictionary in Python

default_data['item3'] = 3

Easy as py.

Another possible solution:

default_data.update({'item3': 3})

which is nice if you want to insert multiple items at once.



Related Topics



Leave a reply



Submit