python : how to disable auto sort when creating dictionary - python

i need help for this case :
m={}
m[1]=1
m[333]=333
m[2]=2
# Result:
{1: 1, 2: 2, 333: 333}
so even when i didn't enter '333' the last, i got this '333' listed in the end of the dictionary when print it out. why is this 'dictionary' doing auto sort? and how disable it? i can creata a function to re-sort to fix the order. but that's not what i want, i just simply want to print and get output order just like the order when i input the data. Is there any good explanation and is there any solution ?

It is not sorting. dict is not ordered at all, so you cannot influence the key order in any way. There is collections.OrderedDict in 2.7 and 3.1+, there is also standalone module for 2.4-2.6.

Items stored in a dictionary do not have any inherent order. The order they are printed out is entirely down to the hash values for each of the keys and the other items in the dictionary.

Long time after this questions was posted, but just for those who land on this page, since 3.6? dictionaries preserve the order that items are added in.

Related

Logic behind accessing dictionary values in python

Rookie here and I couldn't find a proper explanation for this.
We have a simple dict:
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
to loop through and access the values of this dict I have to call
for key in a_dict:
print(key, '->', a_dict[key])
I am saying about
a_dict[key]
specifically. Why python use this convention? Where is a logic behind this? When I want to get values of a dictionary I should call it something like
a_dict[value] or a_dict[values] etc
instead (thinking logically).
Could anyone explain it to make more sense please?
edit:
to be clear: why python use a_dict[key] to access dict VALUE instead of a_dict[value]. LOGICALLY.
according to your question, I think you meant why python does not use index instead of key to reach values in the dict.
Please take note that there are 4 main data container in python, and each for its usage. (there are also other containers like counter and ...)
for example elements of list and tuple is reachable by their indices.
a = [1,2,3,4,5]
print(a[0]) would print 1
but dictionary as its name shows, maps from some objects (keys in python terminology) to some other objects(values in python terminology). so we would call the key instead of index and the output would be the value.
a = { 'a':1 , 'b':2 }
print(a['a']) would print 1
I hope it makes it a bit more clear for you.
I think you are misunderstanding some terminology around dictionaries:
In your example, your keys are color, fruit, and pet.
Your values are blue, apple, and dog.
In python, you access your values by calling a_dict[key], for example a_dict["color"] will return "blue".
If python instead used your suggested method of a_dict[value], you would have to know what your value was before trying to access it, e.g. a_dict["blue"] would be needed to get "blue", which makes very little sense.
As in Feras's answer, try reading up more on how dictionaries work here
Its because, a dictionary in python, maps the keys and values with a hash function internally in the memory.
Thus, to get the value, you've to pass in the key.
You can sort of think it like indices of the list vs the elements of the list, now to extract a particular element, you would use lst[index]; this is the same way dictionaries work; instead of passing in index you would've to pass in
the key you used in the dictionary, like dict[key].
One more comparison is the dictionary (the one with words and meanings), in that the meanings are mapped to the words, now you would of course search for the word and not the meaning given to the word, directly.
You are searching for a value wich you don't know if it exists or not in the dict, so the a_dict[key] is logic and correct

Am I using `all` correctly?

A user asked (Keyerror while using pandas in PYTHON 2.7) why he was having a KeyError while looking in a dictionary and how he could avoid this exception.
As an answer, I suggested him to check for the keys in the dictionary before. So, if he needed all the keys ['key_a', 'key_b', 'key_c'] in the dictionary, he could test it with:
if not all([x in dictionary for x in ['key_a', 'key_b', 'key_c']]):
continue
This way he could ignore dictionaries that didn't have the expected keys (the list of dictionaries is created out of JSON formatted lines loaded from a file). *Refer to the original question for more details, if relevant to this question.
A user more experienced in Python and SO, which I would consider an authority on the matter for its career and gold badges told me I was using all incorrectly. I was wondering if this is really the case (for what I can tell, that works as expected) and why, or if there is a better way to check if a couple of keys are all in a dictionary.
Yes that will work fine, but you don't even need the list comprehension
if not all(x in dictionary for x in ['key_a', 'key_b', 'key_c']):
continue
If you have the surrounding [], it will evaluate all the elements before calling all. If you remove them, the inner expression is a generator, and will short-circuit upon the first False.

How to set value in python dictionary while looking it up from another dictionary?

I have two dictionaries. The first is mapping_dictionary, it has several key-value pairs. It will serve as a reference. The second dictionary only has two key-value pairs. I would like to look up the value that should be assigned to the second dictionary in the mapping_dictionary and set it to one of the values. I tried doing it a few different ways but no success.
Please let me know if the syntax is wrong or if this is not the way to do something like this in Python? Thank you in advance for any help.
Example 1:
mapping_dictionary={'TK_VAR_DEC':1, 'TK_ID':2, 'TK_COMMA':3}
token_dictionary={'TK_TYPE', 'TK_VALUE'}
tk_v=mapping_dictionary.get("TK_VAR_DEC")
token_dictionary['TK_TYPE']=tk_v
token_dictionary['TK_VALUE']="VAR_DEC"
Example 2:
token_dictionary['TK_TYPE']=mapping_dictionary.get("TK_VAR_DEC")
token_dictionary['TK_VALUE']="VAR_DEC"
With the definition of the token_dictionary, you're not defining a dictionary at all -- you've written the literal syntax for a set. You need to specify values for it to be a dictionary. I expect that if you change to using token_dictionary = {'TK_TYPE': None, 'TK_VALUE': None} you'll have more luck.
Also note that using .get() is unnecessary for retrieving a value from the dictionary. Just use [].

Python Dictionary with Variable Array keys

self.PARSE_TABLE={"$_ERROR":self.WEEK_ERRORS,"$_INFORM":self.WEEK_INFORM,"$_REDIR":self.WEEK_REDIRECTS,"$_SERVER_ERROR":self.WEEK_SERVER_ERROR,"$_BYTES":self.WEEK_BYTES,"$_HITS":self.WEEK_HITS}
for j in self.PARSE_TABLE:
print j
break
When I run this on my python the first element I get is S_REDIR can someone explain why?
Dictionaries don't maintain order. The order you get from iterating over them may not be the order in which you inserted the elements. This is the price you pay for near-instant lookup of values by key. In short, the behavior you are seeing is correct and expected, and may even vary from run to run of the Python interpreter.
It normal behaviour. Inside dictionary and set using hash codes. If you want orderd keys use self.PARSE_TABLE.keys.sort(). Also you can use OrderedDict from collection library.
Dictionary by default stores all the keys in its own convenient order rather to the order we gave.
If the order of the keys should be maintained, you can use OrderedDict which came to implementation from the python version 3.0
P.S. I don't think sorting keys would do any help in preserving the order given.

python dictionary sorting oddly (want non-alphabetical)

so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'm not sure why.
I'm currently using this function to try and achieve this.
def array_sort(array, sort): #yeah, it's array cuz i php like that.
ordered = {}
for i in range(0,len(sort)):
if sort[i] in array:
ordered[sort[i]] = array[sort[i]]
keys = array.keys()
return ordered
order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
keys = array_sort(infos, order)
for some reason this isn't working, infos is the list of keys in alphabetical order, i'm just not sure why the function is outputting the keys in an odd order. (a first, when 15 should be first :S)
If you know a better way to do this feel free to tell me, I just recently started on python, so I'm not that familiar.
EDIT:
I was able to print the keys in the correct order using this immediately after making the order dictionary. even if it was just output as a string the order would be preserved (for the time being) and you could .split() it again to get the dictionary in the correct order (i think).
for i in range(0, len(order)):
if order[i] in infos:
packet += order[i] + '="' + infos[order[i]] + '" '
Since dictionaries in Python are unordered and all that you need is to output results ordered by the specified rule you can do something like this:
order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
for key in order:
print key, infos.get(key)#if infos is your dictionary
Or you can get/pass list instead of dict the following way:
print [(key, infos.get(key)) for key in order]
Python dictionaries are not ordered containers. Take a look at the collections.OrderedDict instead
Python dictionaries order their keys based on its hash, which will make it seem random. I recommend using OrderedDict to get your keys in order.

Categories