Should I use a list or a dictionary? - python

I've read the question already about using a list, dictionary or a tuple but it doesn't answer my specified question
if I wanted an array say with the values of
array(1,2,3,4, "name" => "someone", "age" => array())
should I use a list or a dictionary? also, is it possible to have a multidimensional list or dictionary?
Order does matter here, also, I want to be able to access them using the key, for example
array["name"] would return "someone"

Seeing your use-case only a dictionary would help, because what you are expecting is to pass a key not an index to array. And only a dict takes key against which it returns a value. Unlike list which take in an index.

Related

Changing order of dictionaries keys based on preferred order

The input is a dictionary, for example:
{'first_name':'Jane', 'occupation': 'astronaut', 'age':27, 'last_name':'Doe'}
The keys need to be rearranged to be in a specific order, given in a list, for example:
preferred_order = ['first_name', 'last_name', 'age', 'location']
The dictionary might not have all the keys in the preferred_order list, and might have keys that don't appear on the list.
In this specific case, the result of the sorting should be:
{'first_name':'Jane', 'last_name':'Doe', 'age':27, 'occupation': 'astronaut'}
Key location didn't get added to the dictionary, and the keys not in preferred_order are at the end.
Suggested algorithm:
Create a new, initially empty, dictionary;
Iterate through preferred_order: for every key in preferred_order, add key: value to the new dictionary if it exists in the old dictionary, and remove it from the old dictionary;
for every remaining key: value pair in the old dictionary, add it to the new dictionary.
For step 3, you can use dict.update or |=.
Further reading:
documentation on dict.update and |=;
more about |=;
How do I sort a dictionary by value?;
You can search for "sort dictionary by key" on stackoverflow, but be aware that most answers are outdated and recommend using collections.OrderedDict instead of dict, which is no longer necessary since Python 3.7.

How to facilitate dict record filtering by dict key value?

I want to interface with rocksdb in my python application and store arbitrary dicts in it. I gather that for that I can use something like pickle to for serialisation. But I need to be able to filter the records based on values of their keys. What's the proper approach here?
so let's say you have a list of keys named dict_keys and you have a dict named big_dict and you want to filter out only the values from dict_keys. You can write a dict comprehension that iterates through the list grabbing the items from the dict if they exist like this:
new_dict = {key: big_dict.get(key) for key in dict_keys}
RocksDB is a key-value store, and both key and value are binary strings.
If you want to filter by given keys, just use the Get interface to search the DB.
If you want to filter by given key patterns, you have to use the Iterator interface to iterating the whole DB, and filter the records with keys that match the pattern.
If you want to filter by values or value patterns, you still need to iterating the whole DB. For each key-value pair, deserialize the value, and check if it equals to the give value or matches the give pattern.
For case 1 and case 2, you don't need to deserialize all values, but only values that equal to the give key or match the pattern. However, for case 3, you have to deserialize all values.
Both case 2 and case 3 are inefficient, since they need to iterate the whole key space.
You can configure RocksDB's key to be ordered, and RocksDB have a good support for prefix indexing. So you can efficiently do range query and prefix query by key. Check the documentation for details.
In order to efficiently do value filter/search, you have to create a value index with RocksDB.

How do I use a python dictionary object in MATLAB?

I'm playing with the new capability in MATLAB 2014b where you can call python directly from matlab and get python objects in the workspace (like you've been able to with Java for a long time). I have successfully called a function and gotten a dictionary into the workspace, but I'm stuck on how to harvest the values from it. In this case I have a dictionary full of dictionaries, so I can't just convert it to MATLAB cells like they do in their example.
So a specific question: if I have a dictionary in MATLAB called "A", how to I get the sub-dictionary A['2'] out?
By consulting the MATLAB External Interfaces documentation, the Python dict type is essentially the same interface as a containers.Map. You need to use the values function to extract the value that you want for a certain key. As such, you would call values like so, given that your Python dictionary is stored in A and you want to use '2' as the key to index into your dictionary:
val = values(A, '2');
As such, val would contain what the associated value is with the key of '2'. MATLAB also has the ability to use multiple keys and it would return multiple values - one per key. Therefore, you could also do something like this:
val = cell(values(A, {'1', '2', '3'}));
val would be a three element cell array, where each element is the value for the associated keys that you input in. It is imperative that you convert the output of values into a cell array, because this would normally be a list in Python. In order to use these results in MATLAB, we need to convert to a cell.
Therefore, val{1} would be the dictionary output when you used '1' as the key. Similarly, val{2} would be the dictionary output when you used '2' as the key and so on.
Here are some more operations on a containers.Map object for you. If you want all of the keys in a dictionary, use the keys function:
k = keys(A);
If you were to just use values with the dictionary by itself, like so:
val = cell(values(A));
It would produce all values for every key that exists in your dictionary stored into a cell array.
If you wanted to update a particular key in your Python dictionary, use the update function:
update(A,py.dict(pyargs('4',5.677)));
Here, we use the dictionary A, and update the key-value pair, where the key is '4' and the new value is 5.677.

Ordered Dictionary with list as values

I want to create an ordered dictionary with a List as the value type.
I tried to call this method:
ordered = collections.OrderedDict(list)
but I get the error:
TypeError: 'type' object is not iterable
Is there any other data structure I can use for an ordered dictionary?
Later in the program I need to get the first key/value pair that was inserted; that's why I need the list ordered. After that point order does not matter.
Python is dynamically typed. You don't need to specify the value type in advance, you just insert objects of that type when needed.
For example:
ordered = collections.OrderedDict()
ordered[123] = [1,2,3]
You can get the first inserted key/value with next(ordered.iteritems()) (Python 2) or next(ordered.items()) (Python 3).

Why doesn't Python hash lists using ID?

When using a dictionary in Python, the following is impossible:
d = {}
d[[1,2,3]] = 4
since 'list' is an unhashable type. However, the id function in Python returns an integer for an object that is guaranteed to be unique for the object's lifetime.
Why doesn't Python use id to hash a dictionary? Are there drawbacks?
The reason is right here (Why must dictionary keys be immutable)
Some unacceptable solutions that have been proposed:
Hash lists by their address (object ID). This doesn’t work because if you construct a new list with the same value it won’t be found; e.g.:
mydict = {[1, 2]: '12'}
print mydict[[1, 2]]
would raise a KeyError exception because the id of the [1, 2] used in the second line differs from that in the first line. In other words, dictionary keys should be compared using ==, not using is.
It is a requirement that if a == b, then hash(a) == hash(b). Using the id can break this, because the ID will not change if you mutate the list. Then you might have two lists that have equal contents, but have different hashes.
Another way to look at it is, yes, you could do it, but it would mean that you could not retrieve the dict value with another list with the same contents. You could only retrieve it by using the exact same list object as the key.
In Python dictionaries keys are compared using ==, and the equality operator with lists does an item-by-item equality check so two different lists with the same elements compare equal and they must behave as the same key in a dictionary.
If you need to keep a dictionary or set of lists by identity instead of equality you can just wrap the list in a user-defined object or, depending on the context, may be you can use a dictionary where elements are stored/retrieve by using id explicitly.
Note however that keeping the id of an object stored doesn't imply the object will remain alive, that there is no way for going from id to object and that id may be reused over time for objects that have been garbage collected. A solution is to use
my_dict[id(x)] = [x, value]
instead of
my_dict[id(x)] = value

Categories