0

So Lets say I have a dictionary it contains:

{'h': 2, 'e': 1, 'l': 4, 'o': 4, ',': 1, ' ': 3, 'w': 2, 'r': 1, 'd': 1, '!': 1, 'n': 1, 'g': 1, '.': 3, '\n': 1}

and I want to swap my keys and values so that way the frequency is in the front. What would be the best way to do this. I tried this.

my_dict2 = {y: x for x, y in letter_frequency.items()}

and got

{2: 'w', 1: '\n', 4: 'o', 3: '.'}

so it's clearly not working.

Here is my full code to read in the letter frequency. If there is a way to do it without swamping the keys and values that might be best.

word_list = []

file = open(file_name, 'rU')

for line in file:
    for word in line:
       word_list.append(word);

letter_frequency = {}

for word in word_list:
    for letter in word:
        keys = letter_frequency.keys()
        if letter in keys:
            letter_frequency[letter] += 1
        else:
            letter_frequency[letter] = 1

print(letter_frequency)
my_dict2 = {y: x for x, y in letter_frequency.items()}
print(my_dict2)

return letter_frequency
jpp
  • 159,742
  • 34
  • 281
  • 339
David Dennis
  • 702
  • 2
  • 9
  • 26
  • 8
    What do you want as your result for your duplicate values? Do you want each key to be mapped to a `list` or `set` of values? Remember a dictionary cannot have duplicate keys. – jpp Apr 11 '18 at 16:11
  • Being new to python I did not know that. Great answer. – David Dennis Apr 11 '18 at 16:17
  • fyi: `so it's clearly not working` is not a question on this website. If you had stated the desired output, and said: `Why do I not get what I want?` then you would have been much closer to a question. – quamrana Apr 11 '18 at 16:19

1 Answers1

1

assume you want to save all dupe keys to list

data = {'h': 2, 'e': 1, 'l': 4, 'o': 4, ',': 1, ' ': 3, 'w': 2, 'r': 1, 'd': 1, '!': 1, 'n': 1, 'g': 1, '.': 3, '\n': 1}

d = {}
for k, v in data.iteritems():
    d.setdefault(v, []).append(k)

print d

{1: ['\n', ',', '!', 'e', 'd', 'g', 'n', 'r'],
 2: ['h', 'w'],
 3: ['.', ' '],
 4: ['l', 'o']}
galaxyan
  • 5,944
  • 2
  • 19
  • 43