I have created 3 different dictionary in python , however I believe this cannot be merged into 1 dictionary e.g. NewDict due to a same Key in all 3 e.g. Name & Company.
NewDict1 = {'Name': 'John,Davies', 'Company': 'Google'}
NewDict2 = {'Name': 'Boris,Barry', 'Company': 'Microsoft'}
NewDict3 = {'Name': 'Humphrey,Smith', 'Company': 'Microsoft'}
I would like to group above in such a way that my output is as below :
Google : John Davies Microsoft : Boris Barry, Humphrey Smith
Any help will be really appreciated .
Use a defaultdict:
from collections import defaultdict
dicts = [NewDict1, NewDict2, NewDict3]
out = defaultdict(list)
for d in dicts:
out[d['Company']].append(d['Name'])
dict(out)
output: {'Google': ['John,Davies'], 'Microsoft': ['Boris,Barry', 'Humphrey,Smith']}
as printed string
for k,v in out.items():
print(f'{k}: {", ".join(v)}')
output:
Google: John,Davies
Microsoft: Boris,Barry, Humphrey,Smith
Why don't you use a different structure for your source dictionary ?
like instead of {'name': 'jack', 'company': 'google'}, go for
dict1 = {'Google': ['Jack']}
dict2 = {'Microsoft': ['Susan']}
dict3= {'Google': ['Amit']}
#then you can combine all three dict into one:
def combine_dict(dict_1, dict_2):
for key in dict_1:
val = dict_1[key]
if key in dict_2:
dict_2[key].extend(val)
else:
dict_2[key] = val
return dict_2
new_dict = combine_dict(dict1,dict2)
new_dict = combine_dict(new_dict, dict3)
this should do it
NewDict1 = {'Name': 'John,Davies', 'Company': 'Google'}
NewDict2 = {'Name': 'Boris,Barry', 'Company': 'Microsoft'}
NewDict3 = {'Name': 'Humphrey,Smith', 'Company': 'Microsoft'}
d = {}
l = [NewDict1, NewDict2, NewDict3]
for each in l:
if each['Company'] not in d.keys():
d[each['Company']] = []
if each['Name'] not in d[each['Company']]:
d[each['Company']].append(each['Name'])
Outputs:
d
{'Google': ['John,Davies'], 'Microsoft': ['Boris,Barry', 'Humphrey,Smith']}
For Plain text
output = ''
for k,v in d.items():
v = [x.replace(',',' ') for x in v]
output+=f" {k}:{','.join(v)}"
output = output.strip()
Print(output) and you get:
'Google:John Davies Microsoft:Boris Barry,Humphrey Smith'
Related
I have a list:
List_ = ["Peter", "Peter", "Susan"]
I want to make a dictonary like this:
Dict_ = {"Name": "Peter", "Count": 2, "Name": "Susan", "Count": 1}
Dict_ = {}
Dict_new = {}
for text in List_:
if text not in Dict_:
Dict_[text] = 1
else:
Dict_[text] += 1
for key, values in Dict_.items():
Dict_new["Name"] = key
Dict_new["Count"] = values
print(Dict_new)
It is printing only last ones:
{"Name": "Susan", "Count": 1}
Here is the implementation that you can use according to what you would like :
from collections import Counter
# Your data
my_list = ["Peter", "Peter", "Susan"]
# Count the occurrences
counted = Counter(my_list)
# Your format
counted_list = []
for key, value in counted.items():
counted_list.append({"Name": key, "Count": value})
print(counted_list)
And output will be :
[{'Name': 'Peter', 'Count': 2}, {'Name': 'Susan', 'Count': 1}]
As noted in comments, a dictionary can only have each key once.
You may want a list of dictionaries, built with help from collections.Counter and a list comprehension.
>>> from collections import Counter
>>> List_ = ["Peter", "Peter", "Susan"]
>>> [{'name': k, 'count': v} for k, v in Counter(List_).items()]
[{'name': 'Peter', 'count': 2}, {'name': 'Susan', 'count': 1}]
In addition to using collections.Counter you could use a defaultdict.
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for n in List_:
... d[n] += 1
...
>>> d
defaultdict(<class 'int'>, {'Peter': 2, 'Susan': 1})
>>> [{'name': k, 'count': v} for k, v in d.items()]
[{'name': 'Peter', 'count': 2}, {'name': 'Susan', 'count': 1}]
You can use the following code to achieve what you are trying to do.
List_ = ["Peter", "Peter", "Susan"]
dict_ = {}
for name in List_:
if name in dict_:
dict_[name] += 1
else:
dict_[name] = 1
print(dict_)
Generates the following output where key is the name and value is the count.
{'Peter': 2, 'Susan': 1}
I have a dictionary with some values that are type list, i need to convert each list in another dictionary and insert this new dictionary at the place of the list.
Basically, I have this dictionary
Dic = {
'name': 'P1',
'srcintf': 'IntA',
'dstintf': 'IntB',
'srcaddr': 'IP1',
'dstaddr': ['IP2', 'IP3', 'IP4'],
'service': ['P_9100', 'SNMP'],
'schedule' : 'always',
}
I need to reemplace the values that are lists
Expected output:
Dic = {
'name': 'P1',
'srcintf': 'IntA',
'dstintf': 'IntB',
'srcaddr': 'IP1',
'dstaddr': [
{'name': 'IP2'},
{'name': 'IP3'},
{'name': 'IP4'}
],
'service': [
{'name': 'P_9100'},
{'name': 'SNMP'}
],
'schedule' : 'always',
}
So far I have come up with this code:
for k,v in Dic.items():
if not isinstance(v, list):
NewDic = [k,v]
print(NewDic)
else:
values = v
keys = ["name"]*len(values)
for item in range(len(values)):
key = keys[item]
value = values[item]
SmallDic = {key : value}
liste.append(SmallDic)
NewDic = [k,liste]
which print this
['name', 'P1']
['srcintf', 'IntA']
['dstintf', 'IntB']
['srcaddr', 'IP1']
['schedule', 'always']
['schedule', 'always']
I think is a problem with the loop for, but so far I haven't been able to figure it out.
You need to re-create the dictionary. With some modifications to your existing code so that it generates a new dictionary & fixing the else clause:
NewDic = {}
for k, v in Dic.items():
if not isinstance(v, list):
NewDic[k] = v
else:
NewDic[k] = [
{"name": e} for e in v # loop through the list values & generate a dict for each
]
print(NewDic)
Result:
{'name': 'P1', 'srcintf': 'IntA', 'dstintf': 'IntB', 'srcaddr': 'IP1', 'dstaddr': [{'name': 'IP2'}, {'name': 'IP3'}, {'name': 'IP4'}], 'service': [{'name': 'P_9100'}, {'name': 'SNMP'}], 'schedule': 'always'}
In my use case, I want to update random data provided with DictB in the Already existing DictA without Changing the hierarchical structure.
dictA = {'Service': {'Name': 'MyService', 'Tag': {'MyTag'}, 'Host': 'myHost'}, 'Route':{}}
dictB = {'Service': {'Name': 'MyService', 'Tag':{'MyTag1','MyTag2','MyTag3'}}}
My code:
dictA.update(dictB)
Output should be:
dictA = {'Service': {'Name': 'MyService', 'Tag': {'MyTag1', 'MyTag2', 'MyTag3'}, 'Host': 'myHost'}, 'Route':{}}
But it's giving me errors saying the structure is not valid.
dictA = {'Service': {'Name': 'MyService', 'Tag': {'MyTag'}, 'Host': 'myHost'}, 'Route':{}}
dictB = {'Service': {'Name': 'MyService', 'Tag':{'MyTag1','MyTag2','MyTag3'}}}
c={}
for x,y in dictA.items():
c[x]=y
for k,v in dictB.items():
c[k]=v
print(c)
you cant change the dictionary A to take union of A & B but you can
create a new dictionary which contains union of dictionary a and b
without changing the hierarchical of A structure.
new_dict1 = dictA['Service']
new_dict2 = dictB['Service']
for k,v in new_dict1.items():
for i,j in new_dict2.items():
if k == i:
if v != j:
if type(v) is list:
v = v + j
new_dict1[k] = list(set(v))
else:
new_dict1[k] = j
print(new_dict1)
Hello I need to compare 2 dicts but in the result, I need to know from which dict the result came.
dict1 = {'name': 'Morgan', 'surename': 'Finch'}
dict2 = {'name': 'David', 'surename': 'Finch'}
so if I compare with input_data.items() ^ response_data.items() result will something like this:
{('name','Morgan'),('name', 'David)}
expected result should look something like {'dict1': ('name','Morgan'), dict2: ('name', 'David')}
I don't care what data-structure just that I could know from what dict it came.
dict1 = {'name': 'Morgan', 'surname': 'Finch'}
dict2 = {'name': 'David', 'surname': 'Finch'}
# symmetric difference (exclusive OR)
print(dict1.items() ^ dict2.items())
# {('name', 'Morgan'), ('name', 'David')}
# dictionary subtraction
print({'dict1': dict1.items() - dict2.items(), 'dict2': dict2.items() - dict1.items()})
# {'dict1': {('name', 'Morgan')} 'dict2': {('name', 'David')}}
If you want the answer in the form of dictionary
You can use these steps
dict1 = {'name': 'Morgan', 'surename': 'Finch'}
dict2 = {'name': 'David', 'surename': 'Finch'}
dict3 = {}
for k,v in dict1.items():
if dict1[k] != dict2[k]:
dict3['dict1'] = (k,dict1[k])
dict3['dict2'] = (k,dict2[k])
print(dict3)
Output:
{'dict1': ('name', 'Morgan'), 'dict2': ('name', 'David')}
Edit:
If all values are different and want to store in a single key like {'dict1' : ('name', 'Morgan', 'surname', 'Finc'), ... }
dict1 = {'name': 'Morgan', 'surename': 'Finch'}
dict2 = {'name': 'David', 'surename': 'Finc'}
dict3 = {'dict1':(), 'dict2':()}
for k,v in dict1.items():
if dict1[k] != dict2[k]:
dict3['dict1'] += (k,dict1[k])
dict3['dict2'] += (k,dict2[k])
print(dict3)
Output:
{'dict1': ('name', 'Morgan', 'surename', 'Finch'), 'dict2': ('name', 'David', 'surename', 'Finc')}
I have below list of dictionaries:
>>> d={}
>>> d['primary info']={"name":"Mark","age":22,"Id":1234}
>>> d['secondary info']={"location":"Pune"}
Now dictionary d has list as following:
{'secondary info': {'location': 'Pune'}, 'primary info': {'age': 22, 'Id': 1234, 'name': 'Mark'}}
How can I remove age key-value pair from primary info?
How can I update value of Id in primary info?
To remove a key, value pair, you can use del:
>>> d = {"bob": "fish", "cat": "dog"}
>>> del d["cat"]
>>> d
{'bob': 'fish'}
As for the second part, you need to get the value of the key "primary info" (another dictionary) and then access the"Id"` value of this, and update it:
d["primary info"]["Id"] = 4321
which I can confirm, updates the value:
{..., 'primary info': {'Id': 4321, 'name': ...}, ...}
To delete a key or value from dict you can use del. For more info regarding del go to this link
You can solve your problem like this..
d={}
d['primary info']={"name":"Mark","age":22,"Id":1234}
d['secondary info']={"location":"Pune"}
del d['primary info']['age'] # deleting
d['primary info']['Id'] = 177 # updating
print(d)
# Output
{'primary info': {'Id': 177, 'name': 'Mark'}, 'secondary info': {'location': 'Pune'}}
Hope this helps..
You can use dictionary comprehension:
d = {'secondary info': {'location': 'Pune'}, 'primary info': {'age': 22, 'Id': 1234, 'name': 'Mark'}}
new_id = 2344
new_d = {a:{c:new_id if c == "Id" else d for c, d in b.items() if c != 'age'} for a, b in d.items()}
Output:
{'primary info': {'Id': 2344, 'name': 'Mark'}, 'secondary info': {'location': 'Pune'}}
Or, you can use recursion for a more robust solution:
def update(d, new_id, delemeter='age'):
if all(not isinstance(b, dict) for a, b in d.items()):
return {a:new_id if a == "Id" else b for a, b in d.items() if a != delemeter}
final_data = {a:update(b, new_id, delemeter=delemeter) for a, b in d.items()}
return final_data
Output:
{'primary info': {'Id': 2344, 'name': 'Mark'}, 'secondary info': {'location': 'Pune'}}