How to Combine Lists Into Python Dictionaries

One of Python's unique object types is the dictionary, which contains collections of other objects that are stored by key rather than by sequence. You can modify dictionaries as well as append and shorten on demand, making them a very powerful type of object. Dictionaries also allow nesting, a feature that enables very detailed information storage within a dictionary file.

Instructions

    • 1

      Create an empty dictionary. In your Python script, type:

      dict = {}

    • 2

      Add a few key pairs to the dictionary. For example, to create a dictionary that describes an employee, you might type:

      dict['name'] = 'Bob Smith'

      dict['job'] = 'programmer'

      dict['age'] = 40

    • 3

      Create another dictionary key that contains a list. In this example, you can change the job type to match the fact that Bob has several job types:

      dict['job'] = ['programmer', 'developer', 'manager']

    • 4

      Type "print dict" (without quotes) to see the dictionary with its nested list:

      {'job': ['programmer', 'developer', 'manager'], 'age': 40, 'name': 'Bob Smith'}

Related Searches:

References

Comments

Related Ads

Featured