How to check if multiple keys exists in nested (all) dictionary? - python-3.x

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

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 do I find character frequency form text file through iteration? (python3)

I'm trying to find a way to iterate through a text file and list to find character frequency. I understand that I could use Count() for this. But Count() gives everything including spaces periods and whatnots. Also it does not show the character frequency in alphabetical order. I found a way to do it and it works but not really. I'll explain later. Also when I try to put the frequency I get a KeyError. I'll also explain.
I don't want to put my whole project on here so I'll explain some stuff first. I have a separate list called alphabet_list which includes the alphabet. There's a text file that is already read through and converted into uppercase called new_text.
Character frequency Code:
for i in range(len(alphabet_list)):
for c in new_text:
if c == alphabet_list[i]:
count += 1
else:
count = 0
print(alphbet_list[i] + " " + str(count)
i += 1
Output
A 0
A 0
.
.
.
A 1
A 0
.
.
.
B 0
.
.
.
B 1
B 2
B 0
.
.
.
Z 0
P.S the str(count) is temporarily there because I want to see how it looks like print out, I needed to store the result in dictionary
My output would be that, like I said it works but not really. It will iterate but it iterates through every letter and prints out the result already and does not iterate the whole text file and just print final result. It will add to the result if there is another letter same as before right next to each other. Ex (... bb...) it will be B 1, B 2 like shown in my output. And for some reason when I use return it doesn't work. It returns nothing and just ends the program.
Second Code with KeyError:
I skipped the problem on top because I couldn't find the answer and didn't want to waste my time but ran into another problem lol*
for i in range(len(alphabet_list)):
for c in new_text:
if c == alphabet_list[i]:
count += 1
else:
count = 0
c_freq[alphabet_list[i]] == count
print(c_freq)
i += 1
This one was pretty simple I got a KeyError: 'A'.
I tried only doing the
i = 3 #just random number to test
count = 50
c_freq[alphabet_list[i]] == count
print(c_freq)
and it works, so I'm thinking that problem is also related to the problem above(? maybe). Anyways any help would be great. Thanks!
Sorry for long question but I really needed help.
This should help you:
lst = ['A', 'Z', 'H', 'A', 'B', 'N', 'H', 'Y', '.' , ',','Z'] #Initial list. Note: The list also includes characters such as commas and full stops.
alpha_dict = {}
for ch in lst:
if ch.isalpha(): #Checks if the character is an alphabet
if ch in alpha_dict.keys():
alpha_dict[ch] += 1 #If key already exists, value is incremented by 1
else:
alpha_dict[ch] = 1 #If key does not exist, a new key is created with value 1
print(alpha_dict)
Output:
{'A': 2, 'Z': 2, 'H': 2, 'B': 1, 'N': 1, 'Y': 1}
Since you want the output to be sorted in alphabetical order, add these lines to your code:
key_list = list(alpha_dict.keys()) #Creates a list of all the keys in the dict
key_list.sort() #Sorts the list in alphabetical order
final_dict = {}
for key in key_list:
final_dict[key] = alpha_dict[key]
print(final_dict)
Output:
{'A': 2, 'B': 1, 'H': 2, 'N': 1, 'Y': 1, 'Z': 2}
Thus, here is the final code:
lst = ['A', 'Z', 'H', 'A', 'B', 'N', 'H', 'Y', '.' , ',','Z']
alpha_dict = {}
for ch in lst:
if ch.isalpha():
if ch in alpha_dict.keys():
alpha_dict[ch] += 1
else:
alpha_dict[ch] = 1
key_list = list(alpha_dict.keys())
key_list.sort()
final_dict = {}
for key in key_list:
final_dict[key] = alpha_dict[key]
print(final_dict)
Output:
{'A': 2, 'B': 1, 'H': 2, 'N': 1, 'Y': 1, 'Z': 2}

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.

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

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