Dictionary

Creating a Dictionary

A dictionary can be created using curly braces {} or the dict function. Note that you cannot use dictionary comprehension to create a dictionary in Python Parser.

  • Method 1: Creating a dictionary using curly braces {}.

    // method 1: curly braces {}
    d = {'A':12, 'B':`halo, 'C': [1,2,3]}
    type(d)

    Output: dict

    d1 = {'alpha':{'A': 1, 'B': 2}, 'num':{1: 2, 2: 3}}

    Output: {'alpha': {'A': 1, 'B': 2}, 'num': {1: 2, 2: 3}}

  • Method 2: Creating a dictionary using the dict function.

    // method 2: dict(iterable, **kwarg)
    d1 = dict([('one', 1), ('two', 2), ('three', 3)]) 
    type(d1)

    Output: dict

Accessing Dictionary Items

Access a dictionary item by referring to its key name.

d['C']

Output: [1,2,3]

d.values()

Updating a Dictionary

  1. Changing dictionary items

    d['B'] = 2022.01.01
    d

    Output: {'A': 12, 'B': 2022.01.01, 'C': [1, 2, 3]}

    d2 = {'A':15, 'D':`YES}
    d.update(d2)
    d

    Output: {'A': 15, 'B': 2022.01.01, 'C': [1, 2, 3], 'D': 'YES'}

  2. Adding dictionary items

    d = {'A':12, 'B':`halo, 'C': [1,2,3]}
    d['D'] = ("math", "chinese", [90, 80])
    d

    Output: {'A': 12, 'B': 'halo', 'C': [1, 2, 3], 'D': ('math', 'chinese', [90, 80])}

  3. Removing dictionary items

    d = {'A':12, 'B':`halo, 'C': [1,2,3]}
    d.pop('A')  // Remove the item with the specified key name

    Output: 12

    d

    Output: {'B': 'halo', 'C': [1, 2, 3]}

    d.clear()
    d

    Output: {}

Getting Available Attributes and Methods of a Dictionary

dir(d)

Output: ['__dir__', '__eq__', '__getitem__', '__init__', '__iter__', '__len__', '__ne__', '__repr__', '__req__', '__rne__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'setdefault', 'toddb', 'update', 'values']

If all keys in a Python Parser dictionary share the same data type and are not of type DOUBLE or FLOAT, you can use toddb, a unique method in Python Parser, to convert this dictionary object into a DolphinDB dictionary.

d = {'A': 12, 'B': 2022.01.01, 'C': [1, 2, 3]}
type(d.toddb())

Output: dolphindb.DICTIONARY.STRING

d = {1: 12, 2: 2022.01.01, 3: [1, 2, 3]}
type(d.toddb())

Output: dolphindb.DICTIONARY.INT