user1812844
user1812844

Reputation: 297

A way to guarantee ordering of key/value list from unordered dictionary?

I have a dictionary, which contains a title and the data. Is there a way to split this data into two lists while keeping the order it was extracted from the dictionary? I have to process the key list and the value list separately, and then I use those lists to build a string.

It's important because I print them out separately, and the output has to match. It doesn't matter if lists are out of order than when they were entered. So long as their positions match in the lists, it's fine.

Here is a very simple example to represent the case:

mydict = {'Hello':1, 'World':2, 'Again':3}
keys = mydict.keys()
values = mydict.values()

print 'The list of keys are: %s' % stringify(keys)
print 'The corresponding values are: %s' % stringify(values)

# Output:
> The list of keys are: Hello, Again, World
> The corresponding values are: 1, 3, 2

I know I can build an ordered dictionary and then getting the key/value ordering will be guaranteed, but I would also like to handle this case as well (non-ordered dictionary).

Upvotes: 2

Views: 203

Answers (4)

Jon Clements
Jon Clements

Reputation: 142136

Just don't mutate the dict and you'll be fine. Otherwise, there's just a twist on what you've done already of:

keys, values = zip(*mydict.items())

Which somehow feels "safer" than two operations...

Upvotes: 1

DSM
DSM

Reputation: 353059

Even though the order you see the pairs in is arbitrary, the output from keys() and values() will always align, assuming you don't modify the dictionary. From the docs:

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). The same relationship holds for the iterkeys() and itervalues() methods: pairs = zip(d.itervalues(), d.iterkeys()) provides the same value for pairs. Another way to create the same list is pairs = [(v, k) for (k, v) in d.iteritems()].

Upvotes: 7

abarnert
abarnert

Reputation: 365707

Just use items, which gives you, effectively, a zipped-together copy of keys and values:

items = mydict.items()

print 'The list of keys are: %s' % stringify([key for key, value in items])
print 'The list of values are: %s' % stringify([value for key, value in items])

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113945

titles = myDict.keys()
allData = [myDict[t] for t in titles]

This way, titles might be in some unpredictable order, but each element in allData will be the data pertaining to the corresponding element in titles

Upvotes: 1

Related Questions