Question: I have this script that is suppose to rank fruits based on a number.

```
#! /usr/bin/python
fruits = {'Apple':1,'Banana':2,'Pineapple':3}
alist = [(v, k) for k, v in fruits.items()]
alist.sort(reverse=False)
fruit_order = str(alist).translate(None, "[]()'123456789").replace(", , ",    "    ,     ",").replace(" ", "")[1:]
print fruit_order

```

fruits is actully a list made up with check with .append(fruits)

```
#! /usr/bin/python
import re
from configobj import ConfigObj
config = ConfigObj('sites.conf')
fruits = []

substance = "juice"
target_list = config['MainConfig']['fruits']
for target in target_list:
  if re.search( config[target]['Skiplist'], substance, re.M|re.I):
     target = target + "'" + ":" + config[target]['Rank'] + ","
     fruits.append(target)
  else:
   print "Dident pass"
fruits1 = "{'" + "'".join(fruits) + "}"
alist = [(v, k) for k, v in fruits1.list()]
alist.sort(reverse=False)
fruit_rank = str(alist).translate(None, "[]()'123456789").replace(", , ", ",").replace(" ", "")[1:]

```

print fruit\_rank in example 2 prints out a line that looks exactly like test in example 1.

But iam still getting an error on example2, AttributeError: 'str' object has no attribute 'list'

And i can not really figure this one out. How would i do it?

What iam looking for is in the config file i have a rank for each fruit, the line should print out the fruits in its rank.

Answer: 
```
fruits = {'Apple': 1,'Banana': 2,'Pineapple': 3}
print ','.join(sorted(fruits, key=fruits.get))

```
You should use the builtin function `sorted`, and specify that you wish to sort by the ranks instead of by the names themselves. For your first example, here is what I would do. It sorts the dict's keys (the fruit names) by its values (their ranks).

```
fruits = {'Apple':1,'Banana':2,'Pineapple':3}
sorted_keys = sorted(fruits.keys(), key=lambda k: fruits[k])

```

Your second example is very hard to read. I would recommend that you comment code that is that complex. 

It looks like you are trying to create a string containing Python code, and then execute that code. Like an `eval` statement. That is not good programming practice. You will want to do something like:

```
fruits = {} # create dict
for line in my_file.readlines():
    fruit_name, rank = function_to_parse_line(line)
    fruits[fruit_name] = rank
sorted_keys = sorted(fruits.keys(), key=lambda k: fruits[k])

```

Now there is a nice separation between the code that reads the data and the code that sorts it. If you wanted to read data from a different kind of file, you can just redefine `function_to_parse_line`.