Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a new key value pair to an existing dictionary?

Tags:

julia

I have some dictionary that already exists. I want to add a new key-value pair, but I do not want to create a new dictionary from scratch.

How can I add a new key-value pair to an existing dictionary in Julia?

like image 886
David Varela Avatar asked Jan 11 '20 22:01

David Varela


People also ask

Can we add key-value pair to a dictionary using the append () function?

Yes, you can append to a dictionary in Python. It is done using the update() method. The update() method links one dictionary with another, and the method involves inserting key-value pairs from one dictionary into another dictionary.

How do I add an item to a dictionary key in Python?

Python add to Dictionary using “=” assignment operator If you want to add a new key to the dictionary, then you can use the assignment operator with the dictionary key. This is pretty much the same as assigning a new value to the dictionary.


1 Answers

Julia uses the common dict[key] = value syntax for setting a key-value pair:

julia> dict = Dict(1 => "one")
Dict{Int64,String} with 1 entry:
  1 => "one"

julia> dict[2] = "two"
"two"

julia> dict
Dict{Int64,String} with 2 entries:
  2 => "two"
  1 => "one"

The same syntax will override a key-value pair if the key already exists:

julia> dict
Dict{Int64,String} with 2 entries:
  2 => "two"
  1 => "one"

julia> dict[1] = "foo"
"foo"

julia> dict
Dict{Int64,String} with 2 entries:
  2 => "two"
  1 => "foo"

dict[key] = value is syntax for a setindex! call. Although not as common, you can call setindex! directly:

julia> dict = Dict(1 => "one")
Dict{Int64,String} with 1 entry:
  1 => "one"

julia> setindex!(dict, "two", 2)
Dict{Int64,String} with 2 entries:
  2 => "two"
  1 => "one"
like image 53
David Varela Avatar answered Jan 01 '23 18:01

David Varela