Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Julia, if I delete! a key and value from a dictionary, will it re-allocate the dictionary?

Tags:

julia

Specifically, I'm interested in speed. If I remove an entry from a dictionary, will it immediately re-allocate the space used by the dictionary? Would it be faster to just set the value to nothing?

like image 668
Daniel Peirano Avatar asked Jan 04 '19 23:01

Daniel Peirano


People also ask

How do you remove a key from a dictionary?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.

How do you check if a key exists in a dictionary Julia?

To test for the presence of a key in a dictionary, use haskey or k in keys(dict) .

What happens when a dictionary has 2 items with the same key value?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.

How does Julia use the dictionary?

A dictionary in Julia can be created with a pre-defined keyword Dict(). This keyword accepts key-value pairs as arguments and generates a dictionary by defining its data type based on the data type of the key-value pairs. One can also pre-define the data type of the dictionary if the data type of the values is known.


1 Answers

If you delete! an entry from the dictionary then it is not re-allocated. Actually dictionary currently does not support shrinking (even empty! does not shrink it) - it can only grow if needed.

This means that you have added a lot of entries to the dict and then removed them then sometimes it would save memory to copy these remaining elements to a new dictionary element by element (but not using copy as it will create copy with the memory footprint that is the same as the source).

Note, however, that if keys or values are not bits type then removing an entry from a dictionary will remove a reference to it (which means that Julia will be able to garbage collect them if there are no other references to them).

like image 142
Bogumił Kamiński Avatar answered Nov 23 '22 11:11

Bogumił Kamiński