0

Let's say I have two dictionaries, one with a set of data and another with the same keys but I want to filter and clean up the data. To be more specific, please take a look at this example of runner's distances:

dict1:{'Bob':'1 mile', 'Barbara':'200 feet', 'Sue':'250 feet'}
dict2:{'Bob':'','Barbara':'','Sue':''}

I would like to strip the value string from each key's value (i.e., the words "mile" and "feet"). I would also like to convert "miles" to "feet" to make sure all units are in feet.

I tried doing a loop such as

for key,val in dict1.items():
    if "mile" in val:
        dict2[key] = float(val[:-6]) * 5280
    else:
        dict2[key] = float(val[:-6]

Unfortunately, while the logic is right, a dictionary is unsorted so it ends up giving me something like:

dict2 = {'Barbara':5280, 'Bob':200, 'Sue':250}

I'd like to know if there is a method to sort both dictionaries (not in alphabetical order or numerical order, but in the order I originally assigned) so that it actually assigns the intended value for each key?

  • Also sorry, I have to point out that it should be "dict1=" and "dict2=" in each line on the first batch of code. – Quack Quack Mar 10 '15 at 21:08
  • Dictionaries are *unordered*. You cannot sort a dictionary. See [Why is the order in Python dictionaries and sets arbitrary?](https://stackoverflow.com/q/15479928). – Martijn Pieters Mar 10 '15 at 21:08
  • You can [edit] your question to fix mistakes. – Martijn Pieters Mar 10 '15 at 21:08
  • Nothing wrong in your assignment/ it shouldn't assign to wrong keys. However to ignore the ' mile' part you need val[:-5] and not val[:-6]. If it is " miles" you would need val[:-6] – user3885927 Mar 10 '15 at 21:15

1 Answers1

0

The keys of a dictionary aren't stored in any particular order; you are free to sort the keys externally any time you wish. Your code is assigning the right values to the right keys.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101