Storing Python dictionary entries in the order they are pushed
Try python 2.7 and above, probably 3.1, there is OrderedDict
http://www.python.org/
http://python.org/download/releases/2.7/
>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1), ('second', 2),
... ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]
PEP 372: Adding an ordered dictionary to collections
How to preserve ordering of items in a python dictionary?
Use OrderedDict class. Example below.
from collections import OrderedDict
dict=OrderedDict()
dict['first']=1
dict['second']=2
dict['third']=3
dict
Python dictionary: are keys() and values() always the same order?
Found this:
If
items()
,keys()
,values()
,
iteritems()
,iterkeys()
, and
itervalues()
are called with no
intervening modifications to the
dictionary, the lists will directly
correspond.
On 2.x documentation and 3.x documentation.
Preserve order of dictionary items as declared in Swift?
In your case an array of custom objects might be more appropriate.
Here is a simple example that should help to get you started:
struct Unit : Printable {
let name: String
let factor: Double
// println() should print just the unit name:
var description: String { return name }
}
let units = [
Unit(name: "kg", factor: 1000.0),
Unit(name: "g", factor: 1.0),
Unit(name: "mg", factor: 0.001),
Unit(name: "lb", factor: 453.592292),
Unit(name: "oz", factor: 28.349523)
]
println(units) // [kg, g, mg, lb, oz]
(I am not sure if the non-metric unit factors are correct :)
Added Keys in the dictionary stored in the correct order
Your for loop is causing the problem here.
for d in range(q)
This kind of construction will have d start at the value 0 and continue until (q-1).
What you want is to start counting from the existing length of your persons city dictionary and increment q times. You can get that length using the len() function and then structure the for loop in the following way:
my_city_len = len(dict[name])
for d in range(my_city_len, my_city_len + q)
You also should take into account that your dictionary keys start counting from 1 and not from 0 and so you have to add 1 to d.
In the end, the looping should looks something like this:
my_city_len = len(dict[name])
for d in range(my_city_len, my_city_len + q):
fav_city = input("Enter your favorite city: ")
dict[name][d+1] = fav_city
print(fav_city, "added")
values and keys guaranteed to be in the consistent order?
Option 1
The current Julia source code indicates that the keys and vals of a Dict()
object are stored as Array
objects, which are ordered. Thus, you could just use values()
and keys()
separately, as in your question formulation. But, it is dangerous to rely on under the hood implementation details that aren't documented, since they might be changed without notice.
Option 2
An OrderedDict
from the DataStructures
package (along with the functions values()
and keys()
) is probably the simplest and safest way to be certain of consistent ordering. It's ok if you don't specifically need the ordering.
Option 3
If you don't want to deal with the added hassle of installing and loading the DataStructures
package, you could just use Julia's built in syntax for handling this kind of thing, e.g.
Mydict = Dict("a" => 1, "b" => 2, "c" => 1)
a = [(key, val) for (key, val) in Mydict]
The use of zip()
as given in the question formulation just adds complexity and risk in this situation.
If you want the entities separate, you could then use:
Keys = [key for (key, val) in Mydict]
Values = [val for (key, val) in Mydict]
or just refer to a[idx][1]
for the idx
element of Keys
when you need it.
Will Dict Return Keys and Values in Same Order?
It's hard to improve on the Python documentation:
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If
items()
,keys()
,values()
,iteritems()
,iterkeys()
, anditervalues()
are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of(value, key)
pairs usingzip(): pairs = zip(d.values(), d.keys()).
The same relationship holds for theiterkeys()
anditervalues()
methods:pairs = zip(d.itervalues(), d.iterkeys())
provides the same value for pairs. Another way to create the same list ispairs = [(v, k) for (k, v) in d.iteritems()]
So, in short, "yes" with the caveat that you must not modify the dictionary in between your call to keys()
and your call to values()
.
Related Topics
How to Activate Virtualenv in Linux
In Python Script, How to Set Pythonpath
Get the Olson Tz Name For the Local Timezone
"Is" Operator Behaves Unexpectedly With Integers
How to Make Function Decorators and Chain Them Together
Running Shell Command and Capturing the Output
I'M Getting an Indentationerror. How to Fix It
What's the Difference Between 'Raw_Input()' and 'Input()' in Python 3
Multiprocessing VS Threading Python
What Is the Purpose of the Return Statement? How Is It Different from Printing
Does Python Support Short-Circuiting
How to Split a Dataframe String Column into Two Columns