badc0re
badc0re

Reputation: 3523

how to keep the structure of the dictionary

Well i have the following dictionary:

 {'3d1011c0bade5f0a064f7daeef09e7acf900cfe8af09e025859b3426': ['mils news 02122002_0005.txt', 1] }

Where

 ['mils news 02122002_0005.txt', 1]

is a list. And now i have the following:

result_array = {k: db_array.get(k, 0)[1] + db_array.get(k, 0)[1] for k in set(db_array) | set(db_array)}

with this i want to sum the number that is in the list with another dictionary. So my question is how to keep the dictionary unchanged, coz i get the following:

{'3d1011c0bade5f0a064f7daeef09e7acf900cfe8af09e025859b3426': 2}

as a result.

Expected output:

{'3d1011c0bade5f0a064f7daeef09e7acf900cfe8af09e025859b3426': ['mils news 02122002_0005.txt', 2] }

According to the first answer of the user, tnx for the solution but i get the following for different keys:

db_array = {'a': ['mils news 02122002_0005.txt', 3]}
>>> result_array = {'b': ['mils news 02122002_0005.txt', 3]}
>>> result_array = {k: [db_array[k][0],db_array[k][1] + result_array.get(k, ['', 0])[1]] for k in set(db_array) | set(result_array)}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
KeyError: 'b'

Upvotes: 1

Views: 179

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124100

Include the db_array[k][0] value in your dict generator expression:

dv = ['', 0]
result_array = {k: [
        db_array.get(k, result_array.get(k))[0],
        db_array.get(k, dv)[1] + result_array.get(k, dv)[1]
    ] for k in set(db_array) | set(result_array)}

Note that I updated the default value to ['', 0] (and used a variable for that to increase readability) if the key is not already present in either dict. Note that for the first item in the list we fall back to result_array if the key was not present in db_array; the key is always present in at least one of the two dicts, this way you do not end up with empty string values.

If the key were not in the result_array dict, then your original default would cause problems, as you use an int 0 to then index as an array:

>>> result_array.get('foobar', 0)[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable

(Updated to reflect your comment showing your original code).

Upvotes: 3

Related Questions