Can I modify the keys in a dictionary directly for Python?

Would this dictionary be possible in python? when keys are unique and immutable.?

  • If I make: A dictionary to map from a given first name to a list of the last names of all students in class with that first name. (would this be possible?)

  • Answer:

    yes, you'd just use a dict with the first names as index and a list of last names as values: {'john': ['aaa', 'bbb', 'ccc'], '', 'jack': ['xxx', 'yyy']} # and so on... a nice way to add new names is to use the setdefault-mehod when adding: names = {} # if names has no key 'john', add it and set it's value to an empty list, # then append 'doe' to that list: names.setdefault('john', []).append('doe') names.setdefault('john', []).append('smith') print names # prints: {'john': ['doe', 'smith']} or you could use a collections.defaultdict, which does basically the same.

IYSman50 at Yahoo! Answers Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.