Hossain
Hossain

Reputation: 255

Python dictionary single key with multiple values possible?

I have an issue with dictionary for single key but multiple values. I am pursing some data from a sqlite3 database table (bacnet_props) having 3 columns. 1st column has 6 entries each having the same key (e.g; object_id[81]). The object_ids are 80,81,82,112,113,114. 2nd column has 6 entries each having a different prop_id, so 6 different value (2501-2510) and then 3rd column has 6 different entries each having a different value so 6 different values again (integer/string). Now I am trying to purse those values in the 2nd column and 3rd column by calling the object_id in the 1st column and make a comparison with my expected values for validation purpose. I am trying to use the following code which just gives me the entries with the key once meaning 1 out of 6 entries from all those 3 columns. Can you guys help me solving this issue?

db_cursor = conn.execute("SELECT * from bacnet_props")
for row in db_cursor:
    observed_output[row[0]]=row[1:3]

The output I get is:

{80: (2510, '2'), 81: (2510, '4'), 114: (2510, '108'), 113: (2510, '105'), 
112: (2510, '103'), 82: (2510, '8')}

The output I expect is:

enter code here
 {80: (2501, '1'), 80: (2502, '4'), 80: (2503, 'LivingRoom'), .......
  81: (2501, '2'), 81: (2502, '5'), 81: (2503, 'FreeSpace'), ........
 ....................................................................
  114: (2501, '1'), 114: (2502, '4'), 114: (2503, 'BackYard' )...etc.. 

I understood that it is due to the fact that dictionary takes only 1 value for a single key. But can anyone suggest me a workaround for this? thanks!

Upvotes: 2

Views: 169

Answers (1)

blhsing
blhsing

Reputation: 107124

A typical workaround is to make the data structure a dict of lists instead:

observed_output = {}
for row in db_cursor:
    observed_output.setdefault(row[0], []).append(row[1:3])

so that you would get, for example:

{
    80: [(2501, '1'), (2502, '4'), (2503, 'LivingRoom')],
    81: [(2501, '2'), (2502, '5'), (2503, 'FreeSpace')], 
    ...
}

Another option is to make the prop_id part of the key too by making a tuple of (object_id, prop_id) a key:

observed_output = {}
for row in db_cursor:
    observed_output[row[:2]] = row[2]

so that you would instead get:

{
    (80, 2501): '1',
    (80, 2502): '4',
    (80, 2503): 'LivingRoom',
    (81, 2501): '2',
    (81, 2502): '5',
    (81, 2503): 'FreeSpace',
    ...
}

And a third option would be to make the data structure a dict of dicts and make prop_id the key of the sub-dicts:

observed_output = {}
for row in db_cursor:
    observed_output[row[0]][row[1]] = row[2]

so that you would get:

{
    80: {
        2501: '1',
        2502: '4',
        2503: 'LivingRoom'
    },
    81: {
        2501: '2',
        2502: '5',
        2503: 'FreeSpace'
    }
}

Upvotes: 2

Related Questions