I have a dictionary with ints for keys, and strings for values. I need to to sort by the strings, so that when I go dict.values() I get the sorted list.
The strings are values like this: 45_12_something_23
I need to sort numbers as numbers and strings as strings. A given row is guaranteed to be either a string or a number (not a mixture).
Whats a good way to do this in python? Performance isnt an issue.
Convert your dictionary to a list of (key,value) pairs. Sort them however you'd like. (Or is that your question - how to do that?) Then insert the sorted (key,value) pairs into a collections.OrderedDict, which will remember the insertion order and use the same order when iterating.
Note that you can't modify the dict you already have, this will make a new dict with the properties you want.
Related
I am presently using a for loop to print all the required key value pairs of a dictionary. However is there a simpler way to select the required key value pair?
for i in (out['elements']):
out = (i['insights'][0]['details']['socialInfo'])
out_temp.append(out)
The content of out is actually a JSON with list of dictionaries and each dictionary contains a list of dictionaries.
You can use map to generate the new list as well. But I think what you are doing is fine, it is much easier to read than the alternatives.
out_temp = list(map(lambda x: x['insights'][0]['details']['socialInfo'], out['elements']))
I cannot see an unequivocally simpler way to access the data you require. However, you can apply your logic more efficiently via a list comprehension:
out_temp = [i['insights'][0]['details']['socialInfo'] for i in out['elements']]
Whether or not this is also simpler is open to debate.
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 have a python dictionary (say dict) in which I keep modifying values (the keys remain unaltered). Will the order of keys in the list given by dict.keys() change when I modify the values corresponding to the keys?
No, a python dictionary has an ordering for the keys but does not guarantee what that order will be or how it is calculated.
Which is why they are not guaranteed to be ordered in the first place.
The values stored in the dictionary do not have an effect on the hash values of the keys and so will not change ordering.
Taken from the Python Documentation:
The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it). To check whether a single key is in the dictionary, use the in keyword.
No, the order of the dict will not change because you change the values. The order depends on the keys only (or their hash value, to be more specific at least in CPython). However, it may change between versions and implementations of Python, and in Python 3.3, it will change every time you start Python.
Python dictionaries' key ordering should not be assumed constant.
However, there are other datastructures that do give consistent key ordering, that work a lot like dictionaries:
http://stromberg.dnsalias.org/~strombrg/treap/
http://stromberg.dnsalias.org/~strombrg/red-black-tree-mod/
BTW, you should not name a variable "dict", because there is a builtin type called "dict" that will be made invisible.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python: Sort a dictionary by value
I am trying to sort a dictionary by its values using sorted(data.items(),key=operator.itemgetter(1))
I manage to sort the values correctly, but I get a list not a dictionary.
Could sb tell me how to sort my dictionary saving dictionary type?
thanks!
Dictionary entries are not ordered. If you want the key-value pairs to be ordered, use a collections.OrderedDict.
As stated before many times, dictionaries can't be sorted.
If you need your dictionary to be sorted for commands such as dict.keys() or dict.values(), use sorted(dict.keys()) or sorted(dict.values()) instead.
If you don't want to do that, the only other option is to use a 2d array, where the format is:
((key, value), (key1, value1), (key2, value2), etc.)