I am on Python 3.9
What I have is two dictionaries.
dict1= {'ZS': [1, 2], 'ZP': [3], 'XS': [4, 5], 'XP': [6, 7]}
dict2= {'a': {}, 'b' : {}}
how do I take every two keys of dict1 and add them as dict-value in dict2.
Like below
required dict
result_dict= {'a': {'ZS': [1, 2], 'ZP': [3]}, 'b' : {'XS': [4, 5], 'XP': [6, 7]}}
The problem of your question is that you didn't explain clearly what is the criteria of the splitting.
Another problem is that when you iniciate a dictionary inside a dictionary, like you did in dict2. if you send 'a' or 'b' values to a variable for example c:
c = dict2['a']
It won't create a new { }, it will pass the reference of the '{ }' inside dict2['a'] or dict2['b'] and when you change c it will change both c and dict2['a'] value
That is quite hacky, got stuck while trying to make a solution hehehe.
If the criteria you are using is the first letter of the key, you can do:
dict1 = {'ZS': [1, 2], 'ZP': [3], 'XS': [4, 5], 'XP': [6, 7]}
dict2 = {'a': {}, 'b': {}}
result_dict = {}
for x in dict2.keys():
result_dict[x] = {}
for key in dict1.keys():
if key[0:1] == "Z":
result_dict['a'][key] = dict1[key]
elif key[0:1] == "X":
result_dict['b'][key] = dict1[key]
print(dict1)
print(dict2)
print(result_dict)
{'ZS': [1, 2], 'ZP': [3], 'XS': [4, 5], 'XP': [6, 7]}
{'a': {}, 'b': {}}
{'a': {'ZS': [1, 2], 'ZP': [3]}, 'b': {'XS': [4, 5], 'XP': [6, 7]}}
You could do something like:
keys1 = list(dict1)
keys2 = list(dict2)
result_dict = {
keys2[i]: {
keys1[2*i]:dict1[keys1[2*i]],
keys1[2*i+1]:dict1[keys1[2*i+1]]
}
for i in range(len(keys2))
}
But in my opinion it is a really bad habit to trust dictionary key's order (unless you use OrderedDict)
Related
e.g.
d1 = {'a':[1, 2, 3], 'b': [1, 2, 3]}
d2 = {'a':[4, 5, 6], 'b': [3, 4, 5]}
The output should be like this:
{'a':[1, 2, 3, 4, 5, 6], 'b': [1, 2, 3, 4, 5]}
If the value repeats itself, it should be recorded only once.
Assuming both dictionaries have the same keys and all keys are present in both dictionaries.
One way to achieve could be:
d1 = {'a':[1, 2, 3], 'b': [1, 2, 3]}
d2 = {'a':[4, 5, 6], 'b': [3, 4, 5]}
# make a list of both dictionaries
ds = [d1, d2]
# d will be the resultant dictionary
d = {}
for k in d1.keys():
d[k] = [d[k] for d in ds]
d[k] = list(set([item for sublist in d[k] for item in sublist]))
print(d)
Output
{'a': [1, 2, 3, 4, 5, 6], 'b': [1, 2, 3, 4, 5]}
If I have list of dicts A:
A = [{ 'a': 1, 'b': 2}, {'a': 3, 'b': 4}]
can I make the following dict:
B = {'a': [1, 3], 'b': [2, 4]}
using only dict/list comprehension?
bonus: can I also account for varied keys in A e.g:
A = [{ 'a': 1, 'b': 2}, {'a': 3, 'b': 4, 'c': 5}]
B = {'a': [1, 3], 'b': [2, 4], 'c': [None, 5]}
I have managed to do this with a for loops and if statements, was hoping for something that processes faster
Try:
A = [{"a": 1, "b": 2}, {"a": 3, "b": 4, "c": 5}]
out = {k: [d.get(k) for d in A] for k in set(k for d in A for k in d)}
print(out)
Prints:
{'a': [1, 3], 'b': [2, 4], 'c': [None, 5]}
Currently I am tidying up one of my projects by using the more pythonic way of dong things. Now I struggle extending a list by values from a dictionary that are lists.
my_dict = {'a': [1, 2, 3], 'b': [2, 3, 4], 'c': [4, 5, 6]}
criteria = ['a', 'c']
my_list = []
for c in criteria:
my_list.extend(my_dict[c])
Results in [1, 2, 3, 4, 5, 6] which is the sought for result, where as
my_list = []
my_list.extend(my_dict[c] for c in criteria)
Results in a nested list [[1, 2, 3], [4, 5, 6]]. I can't quite find a reason why this is happening
Your code does not work because it attempts to extend the list with the result of the generator comprehension, which is a list of lists:
>>> list(my_dict[c] for c in criteria)
[[1, 2, 3], [4, 5, 6]]
This is because my_dict[c] is itself a list.
A more Pythonic way is to use a list comprehension:
my_dict = {'a': [1, 2, 3], 'b': [2, 3, 4], 'c': [4, 5, 6]}
criteria = ['a', 'c']
my_list = [item for k in criteria for item in my_dict[k]]
>>> my_list
[1, 2, 3, 4, 5, 6]
This uses a nested loop to select the values from the dict by criteria and to flatten the lists that are those values.
How would I go in Groovy idiomatically (with collection methods?) from
[['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]
to
[[a: 1, b: 2, c: 3], [a: 4, b: 5, c: 6]]
def x=[['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]
x.tail().collect{v-> x.head().indexed().collectEntries{i,k-> [k, v[i]] } }
I have a list of identical dicts (same keys, same number of keys..) ..like this:
mydict_list = [
{'win32': [2, 45], 'https': [2, 13], 'nofollow': [3, 45], 'href': [4, 847]},
{'win32': [0, 5], 'https': [0, 13], 'nofollow': [1, 5], 'href': [2, 87]}
]
I want to create one dict that has the same keys and values added up nicely....like this:
{'win32': [2, 50], 'https': [2, 26], 'nofollow': [4, 50], 'href': [6, 934]}
Is there an elegant way to do it?
This is what I have working. It works and is readable also:
keys = list(mydict_list[0].keys())
final_dict = {item: [] for item in keys}
for k in list(final_dict.keys()):
v0 = v1 = 0
for d in mydict_list:
for kk, v in d.items():
if k == kk:
v0 += v[0]
v1 += v[1]
final_dict.update({k: [v0, v1]})
Short approach:
lst = [
{'win32': [2, 45], 'https': [2, 13], 'nofollow': [3, 45], 'href': [4, 847]},
{'win32': [0, 5], 'https': [0, 13], 'nofollow': [1, 5], 'href': [2, 87]}
]
res = lst[0] # start with the 1st dict
for d in lst[1:]:
for k, v in d.items():
res[k] = list(map(sum, zip(v, res[k])))
print(res)
The output:
{'win32': [2, 50], 'https': [2, 26], 'nofollow': [4, 50], 'href': [6, 934]}
Consider using a dictionary comprehension on this to make it more "pythonic" (though readability goes down significantly)
d1=[
{'win32': [2, 45], 'https': [2, 13], 'nofollow': [3, 45], 'href': [4, 847]},
{'win32': [0, 5], 'https': [0, 13], 'nofollow': [1, 5], 'href': [2, 87]}
]
Can do it in a a two-liner (and should be mostly generic for almost all cases). Assuming that all the keys are the same across each dictionary in the array.
d2={key:[d[key] for d in d1] for key in d1[0].keys()}
d3={key:[sum(d3) for d3 in list(map(list,zip(*d2[key])))] for key in d1[0].keys()}
print(d3)
{'win32': [2, 50], 'https': [2, 26], 'nofollow': [4, 50], 'href': [6, 934]}
The Explanation
Dictionary comprehensions allow you to collapse your array so that we can work with each key individually.
In the first step, we create d2 which is d1 rearranged by key.
Once you have that in place, d3 the list-map re-arranges the array so that you can sum each list element wise using the built-in sum as part of a list comprehension.
If data was stored as a numpy array, this process would probably go significantly faster (as is, it's a bit memory inefficient).