How do I create an ordered dictionary key from a tuple in Python 2.7?
I have seen a lot of examples about creating a new dictionary from a tuple, or building tuples from dictionary keys but not how to generate a "multi-dimensional key" from a tuple, i.e. use the keys in the tuple to recursively index into a nested dictionary.
Basically I would like to use a tuple such as:
('australia', 'queensland', 'brisbane')
as a dictionary key:
places['australia']['queensland']['brisbane']
The dictionary is an OrderedDict that contains JSON data.
One liner (where t is your tuple and places is your dictionary of dictionaries of dictionaries of...):
reduce(dict.get, t, places)
What's actually happening here is that you're repeatedly getting each element of the tuple t from the dict places.
In python 3, you'll need to import reduce via from functools import reduce.
Related
I am using Python 3.6 to process the data I receive in a text file containing a Dict having sorted keys. An example of such file can be:
{"0.1":"A","0.2":"B","0.3":"C","0.4":"D","0.5":"E","0.6":"F","0.7":"G","0.8":"H","0.9":"I","1.0":"J"}
My data load and transform is simple - I load the file, and then transform the dict into a list of tuples. Simplified it looks like this:
import json
import decimal
with open('test.json') as fp:
o = json.loads(fp.read())
l = [(decimal.Decimal(key), val) for key, val in o.items()]
is_sorted = all(l[i][0] <= l[i+1][0] for i in range(len(l)-1))
print(l)
print('Sorted:', is_sorted)
The list is always sorted in Windows and never in Linux. I know that I can sort the list manually, but since the data file is always sorted already and rather big, I'm looking for a different approach. Is there a way to somehow force json package to load the data to my dict sorted in both Windows and Linux?
For the clarification: I have no control over the structure of data I receive. My goal is to find the most efficient method to load the data into the list of tuples for further processing from what I get.
A dictionary is just a mapping between its keys and corresponding values. It doesn't have any order. It doesn't make sense to say you always find them sorted. In addition, any dictionary member access is O(1) so it's probably fast enough for your need. In case you think you still need some order, ordered dictionary may be useful.
Dicts are unordered objects in Python, so the problem you're running into is actually by design.
If you want to get a sorted list of tuples, you can do something like:
sorted_tuples = sorted(my_dict.items(),key=lambda x:x[0])
or
import operator
sorted_tuples = sorted(my_dict.items(),key=operator.itemgetter(0)
The dict method .items() converts the dict to a list of tuples and sorted() sorts that list. The key parameter to sorted explains how to sort the list. Both lambda x: x[0] and operator.itemgetter(0) select the first element of the tuple (the key from the original dict), and sort on that element.
I have a Dictionary in Python such as this:
dict = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
Is there any way that I can keep the order of this dictionary expressed this way. I have read already several forums and most of them suggest using OrderedDict(). But as explained here:
Python OrderedDict not keeping element order
OrderedDict(dict) will not keep the order when the dictionary is written in that form. I can not manually create the dictionary in an specific way (e.g list of tuples) because it is randomly generated by the code elsewhere.
Thank you very much for you help!!
The moment you write dict = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}, you already have lost the order of the elements. The ways to keep it:
a. Create OrderedDict from your data in the first place.
b. Convert your dict to a list of tuples and sort in a way you want, then create OrderedDict from it.
All in all, from your question it is not clear what you want to preserve. If it is generated "randomly" then who cares, if there is some logic behind it, then use this logic to recreate that order and create OrderedDict using it. If there is something happening behind the scenes which creates this dict from some input data, then, alas, the order in which you see it is not the order in which it has been created.
PS And don't call your dict dict.
If the dictionary you want to order is created outside of your control, you might use the following to get its key:value pairs as a list of tuples:
pairs = my_dict.items()
You can then sort this list any way you like. When you've done that, you can pass the ordered list of pairs to the OrderedDict constructor
from collections import OrderedDict
# sort in some way (for example, reverse the key order)
pairs = reversed(my_dict.items())
ordered = OrderedDict(pairs)
Just use 2 for:
dict = {'a':4, 'q':1, 'l':2, 'm':4, 'p':1}
i = max(dict.values())+1
for el in range (i):
for letter in dict:
if el==dict[letter]:
print(letter,dict[letter])
I've created a dictionary like
d = {1: {"a":1, "b":2}, 2: {"a":1, "b":2}}
I'm looping through objects to create dictionaries like the above.
I also want to create a reverse of the above dictionary while I loop, it should look like
d2 = {{"a":1, "b":2}: 1, {"a":1, "b":2}: 2}
I know that the dictionary is an unhashable type, but at the same time I want the ability to reverse look up values without looping through the dictionary.
Is there some way to do this in python?
I also want to create a reverse of the above dictionary while I loop,
it should look like
No, you can't. All keys to a dictionary should be hash-able and a dictionary is not hash-able
Key's cannot have duplicate entries
Is there some way to do this in python?
Unless you wan't the key's to be dictionary, you can convert to some other data structure. May be frozenset of item lists?
If you need duplicate keys, use frozenset of item lists with MultiMap 1.0.3
And google returned me an implementation of frozen dict, you can use it with MultiMap 1.0.3
I was looking for ways to sort a dictionary and came across this code on a SO thread:
import operator
x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
How does this code work?
When I call iteritems() over a dictionary I get this:
<dictionary-itemiterator object at 0xf09f18>
I know that this is a reference, but how do you use it?
And afaik, in sorted(a,b), as is supposed to be the thing you want to sort, and b would be the indicator for sorting right? How does itemgetter(1) work here?
operator.itemgetter(1) is equivalent to lambda x: x[1]. It's an efficient way to specify a function that returns the value at index 1 of its input.
.iteritems() is a method of a dictionary that returns an iterator over the entries in the dictionary in (key,value) tuple form.
iteritems() is just like items(), except it returns an iterator rather than a list. For large dictionaries, this saves memory because you can iterate over each individual element without having to build up the complete list of items in memory first.
sorted accepts a keyword argument key which is a function used to determine what to compare by when sorting something. In this case, it is using operator.itemgetter, which is like the function version of doing something[1]. Therefore, the code is sorting on the [1] item of the tuples returned by items(), which is the value stored in the dictionary.
Most python built-ins which deal with lists or list like objects also accept iterators, these are like a pointer into the list, which you can advance to the next item in the list with the next() member function. This can be very convenient for infinite lists or very large lists, (either many elements or very large elements,) to keep memory usage down. See http://docs.python.org/library/stdtypes.html#iterator-types
iteritems() gives an iterator into the list of items in the dictionary.
I know it is easy to implement.
I want a dictionary like class, which takes a list of dictionaries in the constructor.
If you read from this dict by key, the dict-class should check the list of dictionaries and return the first value. If none contains this key KeyError should be thrown like a normal dict.
This dictionary container should be read only for my usage.
You seem to be describing collections.ChainMap, which will be in the next version of Python (3.3, expected to go final later this year). For current/earlier versions of Python, you can copy the implementation from the collections source code.
Not really answer to the question: what if you just define method that merge all dictionaries into one? Why make new class for it?
How to merge: How to merge two Python dictionaries in a single expression?
Varargs: Can a variable number of arguments be passed to a function?
You can easily implement this with this logic.
Iterate over all the dictionaries in the list.
For each dictionary, see if it has the required key by using key in value statement.
If value is found, return the value from the function.
If you have iterated over all dictionaries, and value is not found, Raise KeyError exception.