简体   繁体   中英

Iterating dictionary in the order I added items, python

Say I create a dictionary like so:

self.defaultValues = {}
self.defaultValues["A"] = "10"
self.defaultValues["B"] = "100"
self.defaultValues["C"] = "20"
self.defaultValues["D"] = "12.5"

I want to be able to iterate the items in the same order I added them, meaning

for k in self.defaultValues:
     print k

would result in

A
B
C
D

Also, if I have another list, not necessarily of the same length. I want to iterate both the dictionary and the list, and if a value exist in the list I will print it, otherwise I will print if form the dictionary. Its easy to do with a simple

if self.list.count(value) != 0:

But I think there might be a more elegant way to do it.

Thanks!

For the first problem, use an OrderedDict :

from collections import OrderedDict
d = OrderedDict()
d["A"] = "10"
d["B"] = "100"
d["C"] = "20"
d["D"] = "12.5"
for k in d:
    print k

OrderedDict respects the order in which elements were inserted.

For your second question (you should really make separate questions for separate problems), you can use in to test if an object is in the list:

l = [1,2,3,4]
print 1 in l # prints True
print 5 in l # prints False

For the first part of your question, use collections.OrderedDict

For the second, assuming you still care about the order, you can try (and assuming d is the original dict):

tmp_dict = OrderedDict((x, x) for x in l)
tmp_dict.update(d)

You now have, in tmp_dict , the values you care ( tmp_dict.values() will display them).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM