-2

I have a string...

my_string="The way you see people is the way you treat them and the Way you treat them is what they become"

my def should return this:

{2: ['is'],
 3: ['and', 'see', 'the', 'way', 'you'],
 4: ['them', 'they', 'what'],
 5: ['treat'], 
 6: ['become', 'people']}

My solution returns:

{3: {'you', 'see', 'way', 'and', 'the'},
 6: {'become', 'people'}, 
 2: {'is'},
 5: {'treat'}, 
 4: {'what', 'them', 'they'}}

i need to sorted that dictionary by key and change value's class...my values class is {} but i want [] My solution:

def n_letter_dictionary(my_string):
    my_string=my_string.lower().split()
    sample_dictionary={}
    r=[]
    for word in my_string:
        lw=len(word)
        if lw in sample_dictionary:
            sample_dictionary[lw].add(word)
        else:
            sample_dictionary[lw] = {word}

    return sample_dictionary



print(n_letter_dictionary("The way you see people is the way you treat them 
and the Way you treat them is what they become"))

how can i do this?anyone can help?

Hamid
  • 3
  • 2
  • dictionaries cannot be sorted. They are unstructured data containers (at least up to Python 3.6). converting the `set` to `list` is trivial – Ma0 Aug 11 '17 at 07:59
  • The [`collections.OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict) would return the items in the right order, but I'm unsure on how it will print out. You'd also need to create the `OrderedDict` in the end like `return OrderedDict(sorted(sample_dictionary.items(), key=lambda x: x[0]))` – Kendas Aug 11 '17 at 08:02

3 Answers3

1

You have sets, because you create one here:

sample_dictionary[lw] = {word}

You'd need to make it a list there:

sample_dictionary[lw] = [word]

and use .append(), not .add() to add more elements.

Note that your code can be simplified by using dict.setdefault():

def n_letter_dictionary(my_string):
    sample_dictionary = {}
    for word in my_string.lower().split():
        sample_dictionary.set_default(len(word), []).append(word)
    return sample_dictionary

.setdefault() returns the value for a given key; if the key is missing it'll first set that key to the default value provided in the second argument.

If you wanted to only keep unique words you'd have to either convert the sets to lists after the fact with an extra loop:

def n_letter_dictionary(my_string):
    sample_dictionary = {}
    for word in my_string.lower().split():
        sample_dictionary.set_default(len(word), set()).add(word)
    return {l: list(v) for l, v in sample_dictionary.items()}

The last line is a dictionary comprehension; it builds a new dictionary with the same keys, and each set value converted to a list. Note that sets are unordered, so the resulting list will list the unique words in arbitrary order. If you need to preserve the order of the words in the input, then you'll have collect those words into a list, and then apply a technique from How do you remove duplicates from a list in whilst preserving order? to each value.

Dictionaries are otherwise unordered too, just like sets, and can't be sorted. See How can I sort a dictionary by key? for work-arounds.

For example, you could produce an OrderedDict() instance from the sorted (key, value) pairs:

from collections import OrderedDict

def n_letter_dictionary(my_string):
    sample_dictionary = {}
    for word in my_string.lower().split():
        sample_dictionary.set_default(len(word), set()).add(word)
    return OrderedDict((l, list(v)) for l, v in sorted(sample_dictionary.items()))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Dicts are unordered by default in python < 3.7. What you can do is use an OrderedDict. It retains the order of data insertion, and if you insert the data sorted, it will stay sorted.

from collections import OrderedDict
unordered_dict = {
   3: {'you', 'see', 'way', 'and', 'the'},
   6: {'become', 'people'}, 
   2: {'is'},
   5: {'treat'}, 
   4: {'what', 'them', 'they'}}

ordered_dict = OrderedDict()
for key in sorted(unordered_dict.keys()):
    ordered_dict[key] = unordered_dict[key]
0

You can also use Counter() from collections to solve this problem. It will make your life easier.

import collections
c = collections.Counter(mystring.lower().split(' '))
for key in sorted([*c]):
    print("{0} : {1}".format(key, c[key]))
N M
  • 596
  • 4
  • 18