Best way to merge elements of a dictionary python - python

I am facing a problem where I have to merger different elements of a dictionary based on some condition. What is the most pythonic way to achieve that?
For example , I have the below dictionary
dict = {
'a': [element1 , element2]
'b': [element2, element3]
'c': [element4, element5, element1]
'd': []
}
My resulting dictionary should be
dict = {
'a': [element1, element2, element3, element4, element5]
}
What would be the best way to achieve that?
I want to merge them based upon condition which is evaluated by is_compatible method. So lets' say I will merge two elements if this function returns true
Is there a way I can do this?

result = {
'a': list(set().union(*input_dict.values()))
}

I don't clearly get what you want to do, but it seems like you want to combine all lists as a set. You can do something like this:
new_list = []
for element in dict.values():
for value in element:
new_list.append(element)
new_list = list(set(new_list))
new_dict = {
dict.keys[0]: new_list
}
Hope this helps!

Related

How to get to a dict key from a list?

lets say I have the following dict structure and a list of keys.
d = {
'a': {
'b': {
'c': 'value'
}
}
}
keyList = ['a', 'b', 'c']
What is a pythonic way to reference the value of the c key in a dynamic way? In a static way I would say something like d[a][b][c] however if my keyList is dynamic and I need to reference the value at runtime is there a way to do this? the len of keyList is variable.
The main problem is i really don't know what to search. I tried things like dynamic dictionary path but couldn't get anything remotely close
You can use functools.reduce with the input dict as the starting value and dict.get as the reduction function:
from functools import reduce
print(reduce(dict.get, keyList, d))
This outputs:
value
Demo: https://replit.com/#blhsing/QuintessentialAntiqueMath

Sort a dictionary by values in a nested dictionary

I have dictionary like so:
dic = {"first_a" : { "first_b" : {10, 2} } , "second_a" : {"second_b" : {13, 15} } [...] }
I would like to sort the nested dictionary according to the sum of first_b and second_b values.
I can't get my head around this one, could someone provide an helping hand ?
I have tried to use the sorted() function but wasn't able to find the right lambda function to use as key..
Assuming that you meant to have a dictionary like this:
data = {'a': {'b': {2, 10}}, 'c': {'d': {13, 15}}}
You can get what you want like this:
sorted(data, key =lambda k: sum(*dic[k].values()), reverse=True)
However I don't consider this very readable. I would instead do:
def get_sum(k):
vals, *_ = data[k].values()
return sum(vals)
sorted(data, key=get_sum, reverse=True)
When I'm looking at code late at night, too many parentheses == too long to figure out what's happening.
Note that I used values() because I didn't know if your inner keys were constant. If they were, life is even easier. Note this operates on and sorts the keys.

Best way to substitute both K&V based on a map?

Let say we have a map-dict and data-dict :
m = { 1:2, 4:5, 3:7 }
data = { 1:7, 4:1, 3:6 }
we should replace all occurrences both key&val in "data" according to "m" :
data1 = { 2:7, 5:2, 7:6 }
what is the shortest, fast way to do this ?
I was thinking of converting data to list do the replacements and convert back to dict. But even that gets too involved.
Converting list to dict is OK :
dict(zip(lst[0::2], lst[1::2]))
Converting dict to list is :
data.items()
but this one does not return list, but list of tuples, which make things too involved i.e we need to additionally flatten this LoT.
I was wondering if there is a better way, with emphasis on speed/mem.
dict comprehension:
data1 = {m.get(k, k): m.get(v, v) for k, v in data.items()}
Note that {4: 1, 4: 6} in your example is a single element.

Python distinct list of from given attribute is a list of objects

I haven't been able to find this anywhere else.
I have
lst = [
{'n':'Ste', ...}
,{'n':'Mil', ...}
,{'n':'Tob', ...}
,{'n':'', ...}
,{'n':'Ste', ...}
,{'n':'Mil', ...}
]
How can I reduce this to a distinct
['Ste','Tob','Mil','']
Thanks.
It is called set comprehension
{ l['n'] for l in lst }
Looks like the user needs a list.
list({ l['n'] for l in lst })
p.s. this would've been a comment if i had enough reps.

Using dict keys in python as values in a different dict

I would like to create a "translator" type of dict that would assign values that are keys in different dicts, which are nested, to keys in a dict that I created. The problem I run into is that I can't create a value that represents a nested dict key without having to convert that to a string or some other data type, and when I try to use a string as an index to the nested dict, I get an index error. Ideally, my dict would look something like this:
new_dict{
"new_key_1" : ['subdict1']['subdict2']['old_key_1'],
"new_key_2" : ['subdict1']['subdict2']['old_key_2'],
"new_key_3" : ['subdict1']['subdict3']['old_key_3']
}
Then, for each nested dict, I could generate a new dict object with a simple for loop:
for key, value in new_dict.items() :
user_dict_1[key] = OldDict[value]
The nested dicts are very large and I only need a few fields from each, otherwise I could just use the .copy() function to work with the old dicts.
PS- Any help in rewriting this question to be more readable also appreciated.
You're going to need reduce() for this one...
attrmap = {
"new_key_1": ('subdict1', 'subdict2', 'old_key_1'),
...
}
print reduce(lambda x, y: x[y], attrmap[somekey], old_object)
Are you talking something like this?
from pprint import pprint as pp
subdict1 = {'subdict1_item1':1, 'subdict1_item2':2}
subdict2 = {'subdict2_item1':3, 'subdict2_item2':4}
subdict3 = {'subdict3_item1': 5, 'subdict3_item1':6}
olddict = {
'old_key_1': [subdict1, subdict2],
'old_key_2': [subdict1, subdict2],
'old_key_3': [subdict1, subdict3],
}
newdict = {
'new_key_1': olddict['old_key_1'].append('old_key_1'),
'new_key_2': olddict['old_key_2'].append('old_key_2'),
'new_key_3': olddict['old_key_3'].append('old_key_3'),
}
or this
newdict = {
'new_key_1': 'old_key_1',
'new_key_2': 'old_key_2',
'new_key_3': 'old_key_3',
}
def getnew(newkey, newdict, olddict):
if newkey in newdict:
oldkey = newdict[newkey]
if oldkey in olddict:
preitem = olddict[ oldkey ] # returns a list with two items
item = []
item.append([preitem[0]]) # makes subdict1 wrapped in a list
item.append([preitem[1]]) # makes subdict2/3 wrapped in a list
item.append([oldkey])
return item
else:
raise KeyError('newdict has no matching olddict key')
results to:
pp( getnew('new_key_1', newdict, olddict) )
print
pp( getnew('new_key_2', newdict, olddict) )
print
pp( getnew('new_key_3', newdict, olddict) )
[[{'subdict1_item1': 1, 'subdict1_item2': 2}],
[{'subdict2_item1': 3, 'subdict2_item2': 4}],
['old_key_1']]
[[{'subdict1_item1': 1, 'subdict1_item2': 2}],
[{'subdict2_item1': 3, 'subdict2_item2': 4}],
['old_key_2']]
[[{'subdict1_item1': 1, 'subdict1_item2': 2}],
[{'subdict3_item1': 6}],
['old_key_3']]

Categories

Resources