How do i use dictionaries in python?



  • A dictionary is a key-value pair, defined using curly brackets.

    >>> fruits = {'name' : 'orange', 'country' : 'spain'} 
    >>> print(fruits)
    {'name' : 'orange', 'country' : 'spain'}
    

    Add to a dictionary, here add group key to the fruits dictionary with value of citrus.

    >>> fruits['group'] = 'citrus'
    >>> print(fruits)
    {'name': 'orange', 'group': 'citrus', 'country': 'spain'}
    

    You can also nest dictionaries.

    Define a nested dictionary.

    >>> fruits = { 'oranges' : {'group' : 'citrus', 'country' : 'spain'}, 'apples' : {'group' : 'crunchy', 'country' : 'greece'}}
    >>> print(fruits)
    {'oranges': {'group': 'citrus', 'country': 'spain'}, 'apples': {'group': 'crunchy', 'country': 'greece'}}
    

    Print difference dictionary values.

    >>> print(fruits['oranges']['country'])
    spain
    >>> print(fruits['apples']['group'])
    >crunchy
    

Log in to reply
 

© Lightnetics 2024