can I create output, depending on the key of dictionary? - python-3.x

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.

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': ''}}

Replace a text(of any length) with a key(shuffled characters) provided using Python(Permutation encryption)

I'm supposed to do Permutation encryption where I'm provided with a text and a key.
Lets say the
text = "abbdcada"
key = "dcab"
so I have to map something like this (a,b,c,d) -> (d,c,a,b)
so the output of above input should be
output = dccbadbd
I can easily do this if I have text and key of same length but I'm unable to make a logic for text longer than key length.
Can anyone help me plz...
You can use a dictionary for the mapping.
def encrypt(text):
mapping = {'a': 'd', 'b': 'c', 'c': 'a', 'd': 'b'}
return ''.join(mapping[i] for i in text)
>>> encrypt("abbdcada")
'dccbadbd'

Merge Keys by common value from the same dictionary

Let's say that I have a dictionary that contains the following:
myDict = {'A':[1,2], 'B': [4,5], 'C': [1,2]}
I want to create a new dictionary, merged that merges keys by having similar values, so my merged would be:
merged ={['A', 'C']:[1:2], 'B':[4,5]}
I have tried using the method suggested in this thread, but cannot replicate what I need.
Any suggestions?
What you have asked for is not possible. Your keys in the hypothetical dictionary use mutable lists. As mutable data can not be hashed, you cant use them as dictionary keys.
Edit, I had a go to doing what you asked for except the keys in this are all tuples. This code is a mess but you may be able to clean it up.
myDict = {'A':[1,2],
'B': [4,5],
'C': [1,2],
'D': [1, 2],
}
myDict2 = {k: tuple(v) for k, v in myDict.items()}
print(myDict2) #turn all vlaues into hasable tuples
#make set of unique keys
unique = {tuple(v) for v in myDict.values()}
print(unique) #{(1, 2), (4, 5)}
"""
iterate over each value and make a temp shared_keys list tracking for which
keys the values are found. Add the new key, vlaue pairs into a new
dictionary"""
new_dict = {}
for value in unique:
shared_keys = []
for key in myDict:
if tuple(myDict[key]) == value:
shared_keys.append(key)
new_dict[tuple(shared_keys)] = value
print(new_dict) #{('A', 'C'): (1, 2), ('B',): (4, 5)}
#change the values back into mutable lists from tuples
final_dict = {k: list(v) for k, v in new_dict.items()}
print(final_dict)

How can I write a program in Python Dictionary that prints repeated keys values?

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

Resources