How can I write a program in Python Dictionary that prints repeated keys values? - python-3.x

This is my INPUT:
dic1 = {'a':'USA', 'b':'Canada', 'c':'France'}
dic2 = {'c':'Italy', 'd':'Norway', 'e':'Denmark'}
dic3 = {'e':'Finland', 'f':'Japan', 'g':'Germany’}
I want output something like below:
{'g': 'Germany', 'e': [‘Denmark’,’Finland'], 'd': 'Norway', 'c': ['Italy’,'France', 'f': 'Japan', 'b': 'Canada', 'a': 'USA'}

That is programing - you think the steps you need to get to your desired results, and write code to perform these steps, one at a time.
A funciton like this can do it:
def merge_dicts(*args):
merged = {}
for dct in args:
for key, value in dct.items():
if key not in merged:
merged[key] = []
merged[key].append(value)
return merged

Related

Sorting Dictionary by value of key within a key

I want to sort a dictionary by descending order by a value of a key within a key.
In my sample, I want to sort by little 'c'
Here is what I looks like now:
sample = {'A': {'a':22, 'b':24, 'c':80},
'B': {'a':12, 'b':13, 'c':55},
'C': {'a':44, 'b':33, 'c':99}
}
and here is my desired output:
sample = {'C': {'a':44, 'b':33, 'c':99},
'A': {'a':22, 'b':24, 'c':80},
'B': {'a':12, 'b':13, 'c':55}
}
I tried this bit of code by clearly its not right:
newdict = {}
for key, value in sorted(sample.items(), key=lambda item: item['c'], reverse=True):
newdict[key] = value
sample = newdict
Thank you all for the help in solving this little puzzle!
You're close, the key function should be:
key=lambda item: item[1]['c']
Rewritten to be more Pythonic:
sample = dict(sorted(sample.items(), key=lambda item: item[1]['c'], reverse=True))
(The dict constructor can take an iterable of item tuples)

How to check if multiple keys exists in nested (all) dictionary?

To check if 'b' & 'c' exists in 'a' & 'b'.
test = {
'a': {
'b': [1234],
'c': 'some_value'
},
'd': {
'b': [5678],
'c': ''
}
}
Approach1: works as below but not great implementation if nested dictionary are huge in number. And also, You can't exactly notify which element doesn't exist. Let's say, 'c' not in 'a' , 'b' not in 'd' & 'c' not in 'd' . In this case, it fails at second statement (but it doesn't notify that 3rd & 4th statements also fail). I need to get, which all doesn't exist.
try:
v1 = test['a']['b']
v2 = test['a']['c']
v3 = test['d']['b']
v4 = test['d']['c']
except Exception as err:
print(err)
Approach2:
for k,v in test.items():
if 'b' not in v:
print("'b' doesn't exist in {}".format(test[k][v]))
if 'c' not in v:
print("'c' doesn't exist in {}".format(test[k][v]))
Approach1 and Approach2 seem to be not great. Any other better ways to handle it ?
If there are only two levels of nest, could you please try to count occurence of keys in lower-level dicts?
For example:
counter = {}
for el in test.keys():
for subkey in test.get(el).keys():
if subkey not in counter.keys():
counter[subkey] = 1.0
else:
counter[subkey] += 1.0
it'll return
{'b': 2.0, 'c': 2.0}
based on that you can identify duplicated values in your nested keys.
You could then use set to saw on which keys duplicates exist:
dupe keys
counter = {k : v for k, v in counter.items() if v > 1}
#get only values with dupe records
{k:v for k, v in test.items() if len(set(counter.keys()).intersection(v)) > 0}
> {'a': {'b': [1234], 'c': 'some_value'}, 'd': {'b': [5678], 'c': ''}}

can I create output, depending on the key of dictionary?

I have dictionary that looks like this: 'a': 'NPRO,206', 'b': 'PREP,131', 'c': 'PRCL,120', 'd': 'NPRO,66'etc.
I want to create output that will look like this:NPRO:'a,d', PRCL:'c', PREP:'b'
First of all you have to take all the values like NPRO, PRCL, note that they appear more than once. So, If you won't remove the duplicate ones you can end up adding same value to a key twice.
You can use set(), set is just like sets in mathematics. You can't have a duplicate value. Even if i put 1,2,3,3,1 in the set it finally it would look like 1,2,3
Do something like this:
d = {'a': 'NPRO,206', 'b': 'PREP,131', 'c': 'PRCL,120', 'd': 'NPRO,66'}
new_dict = {}
for k in set(val.split(',')[0] for val in d.values()):
for key, value in d.items():
if k in value:
try:
new_dict[k].append(key)
except KeyError as err:
new_dict[k] = [key]
print(new_dict)
This should print this:
{'NPRO': ['a', 'd'], 'PRCL': ['c'], 'PREP': ['b']}
Note:
This code can be improved but as you said you are new, I have kept things simple.

Merging list of dicts in python

I have the dict in python in the following format:
dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
I want output something like this:
dict2 = {'a':20, 'b':10, 'c':15 }
How to do it ?
I think you can do it with for loop efficiently.
Check this:
dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
dict2 = dict()
for a in range(len(dict1)):
dict2[dict1[a].get('Name')] = dict1[a].get('value')
print(dict2)
Output:
{'a': 20, 'b': 10, 'c': 15}
This is the easy way:
dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
dict2={dc['Name']:dc['value'] for dc in dict1}

creating a dict based on two python dicts

I have two python dicts:
payload = {"key1":{"a":"1"},"key2":{"b":"2","c":"3"}}
and
data = {"1":"John","2":"Jacob"}
I would like my output to be:
{"key1":{"a":"John"},"key2":{"b":"Jacob","c":""}}
Any method that I try correctly prints the values, but does not update the output dictionary.
You can do something like this using dict comprehension :
payload = {"key1":{"a":"1"},"key2":{"b":"2","c":"3"}}
data = {"1":"John","2":"Jacob"}
final = {k: {i:data[j] if j in data.keys() else "" for i, j in payload[k].items()} for k in payload}
print(final)
Output:
{'key2': {'b': 'Jacob', 'c': ''}, 'key1': {'a': 'John'}}
There is no single method for this I am aware of, but you can use:
for k, v in payload.viewitems():
payload[k] = {}
for kv, vv in v.viewitems():
payload[k][kv] = data.get(vv, "")
if you then inspect payload it has the contents you are after:
{'key2': {'c': '', 'b': 'Jacob'}, 'key1': {'a': 'John'}}

Resources