-1

Hi so Im trying to do frequency analysis to solve a key. I have a dictionary with all values. I am trying to change the value that occurs the most in the dictionary to 'e' as it occurs the most in the english langugae.

I have searched online and everything i try it does not work so lets say d = {a:54, b: 73, d: 98}

i want to change that d to the letter e.

how do i go about this in my text file? like how do i call the dictionary to implement such a change?

thank you!

coder125
  • 3
  • 4
  • 1
    `d['e'] = d.pop(max(d, key=d.get))` – Steven Rumbalski Apr 06 '20 at 21:54
  • Your question is not fully clear. Are you trying to change the key itself from "d" to "e" or are you trying to change the text file? Are you writing the code on a text file that you want to change? Please clarify and hopefully we can help you! – Jimmy Apr 06 '20 at 21:56
  • Hi thank you both for your answers. So i want to change the text file to 'e', for all the values of d that occur in the text file, but I'm not sure how to implement the dictionary to do this – coder125 Apr 06 '20 at 22:00
  • @StevenRumbalski I tried to assign a varaible to that so that it can pick out the highest letter that appears when the text file changes, would it be d[var] = d.pop(max(d, key=d.get)) to get the letter e instead of printing the value? thank you! – coder125 Apr 06 '20 at 22:12

2 Answers2

0

Here is my solution assuming you want to do this for all letters (not just 'e'):

Obviously, d and frequencies can be extended as needed.

d = {'a':54, 'b': 73, 'd': 98}

# letters in decreasing order of frequency
frequencies = ['E','T','A','O','I','N','S','R','H','D','L','U','C','M','F','Y','W','G','P','B','V','K','X','Q','J','Z']

# get a list of values (the numbers) from the dictionary
values = list(d.values())

# sort the numbers in decreasing order
values.sort(reverse = True)

# build a new dictionary with the sorted letters as keys and sorted values as values.
d = {frequencies[i] : values[i] for i in range(min(len(values), len(frequencies)))}

print(d)

The resulting value of d will be

{'E': 98, 'T': 73, 'A': 54}
DenverCoder1
  • 2,253
  • 1
  • 10
  • 23
  • should i be solving frequency analysis like this? such as having a list from the order of most occuring letters to least? – coder125 Apr 06 '20 at 22:01
  • @coder125 I don't know what will be most helpful for your situation, but this would give a good start. Taking into account English words that can be made is also important (the website http://quipqiup.com/ has an algorithm that does this). – DenverCoder1 Apr 06 '20 at 22:06
0

I found this helpful tip from another post (Getting key with maximum value in dictionary?):

import operator
stats = {'a':1000, 'b':3000, 'c': 100}
max_key = max(stats.iteritems(), key=operator.itemgetter(1))[0]

You can use this to access the key with the highest value, and then do

d['e'] = d[max_key]
d.pop(max_key)

to rename the element.

whege
  • 1,391
  • 1
  • 5
  • 13