0

I have a python dictionary with the following entries:

professions = {Peasant : ["Peasant", 10000], Merchant : ["Merchant", 15000], ...}

Where the keys are id's. Is there a clever way to get a list of the first entries of the value lists? I'd like a function that returns:

["Peasant", "Merchant", ...]

thanks for suggestions

3
  • 1
    Why can't you use the dict keys? Why are the keys repeated in the list values? Commented Sep 29, 2013 at 20:21
  • och, sorry, forgot to mention: the keys are id's Commented Sep 29, 2013 at 20:22
  • I think what @DanielRoseman is asking is what's the point of the first element in each list? They are the same as the key, so why not just have professions = {"Peasant": 10000, ...}? Commented Sep 29, 2013 at 20:51

4 Answers 4

2

The question is quite under-specified, but presuming what you want to do is to extract the first value in each list, it would be:

names = [v[0] for v in professions.values()]
Sign up to request clarification or add additional context in comments.

3 Comments

Jup, that's what I wanted. Thanks
@anhoppe the more concrete way to say that is to accept the answer :)
;-) will do, but have to wait 10min
1

Maybe this is what you are looking for :

[value[0] for value in professions.values()]

Comments

0

If you mean to retrieve all keys of the dict: professions.keys()

Example:

professions = {Peasant : ["Peasant", 10000], Merchant : ["Merchant", 15000]}

print(professions.keys()) #["Peasant", "Merchant"]

Comments

0

Use the .values() method

professions.values()

2 Comments

Without having it tried: wouldn't .values() just return the lists [["Peasant", 1000], ["Merchant", 15000]] ?
yes, you would have to loop through and get list[x][0] where list is the returned list, and x is each list index.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.