1

1) First I am aware that sets and dictionaries don't have an order, the question confuses me and I am trying to figure this out, you can tell from below my efforts to figure out how to solve the problem. 2) I know that the look of the question is poor so sorry in advance, not sure how to make it more tidy here, have spent over half an hour trying to make it in the proper format etc :-) and it is still not as I would like it to be.

Summary: My difficulty is that the question is requiring me to produce a dictionary with values in a certain order so while I can get the answer of specific values. I can do it without the order it asks unless I have misunderstood.

https://courses.edx.org/courses/course-v1:HarvardX+PH526x+1T2020/discussion/forum/02c9dea99fef73e4d6bdb312bb1869352afb68aa/threads/5edbfbc4eac4b40877a1abd4

This is the course question I am referring to, I have tried some of the stuff which is not successful according to the required answer:

(if you don't want to check the link the answer I get from the code is here:

   {' ': 8, 'e': 8, 'i': 5, 'a': 4, 't': 4, 'l': 3, 'u': 3, 'h': 2, 'n': 2, 's': 2, 'r': 2, 'J': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'k': 1, 'm': 1, 'o': 1, 'q': 1, 'p': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})

The lower and upper case letters of the English alphabet should stored as the string variable alphabet.

Consider the sentence 'Jim quickly realized that the beautiful gowns are expensive'. Create a dictionary count_letters with keys consisting of each unique letter in the sentence and values consisting of the number of times each letter is used in this sentence. Count upper case and lower case letters separately in the dictionary.

What is the 3rd value of the dictionary? Hint: remeber that Python is zero indexed!

my answer 1, correct (YAY really dopamine hit)

What is the 8th value of the dictionary? Hint: remeber that Python is zero indexed!

3 correct (YAY I think... why this was after a lot of attempts looking at my answer which then did not make sense)

Note that I accidentally got the 2nd answer correct, and do not know why.

Apparently the order of the Keys in the dictionary need to be in {J :value, i : value} I have tried counter if you see the link which you can see from my initial attempts which fails to provide the required answer, I have tried set(sentence)&set(alphabet) which provides the following 'order' : {'J', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}

I have tried for several days on and off for hours trying things out to no avail, I got hopeful when I saw a few pages ago that from a stack overflow answer see code below gave me hope.... It really did work ONCE in the command line (J,i,m...) but after for some reason it went back to Jabcde....)

I have also found this useful and very short but still I have the problem of the 'order' of the set being as before:

    a = sentence
    b = dict.fromkeys(a[i], 0)
    for i in a[i]:
        b[i] += 1

Counting the occurrence of unique letters in a string in Python 3

Here is more code too.

as you can see at some point I am trying to force an order of some sort which I don't think is possible for the key and value for the question and answer to be happy .

here is more code: in my jungle of confusion.

    import string
    alphabet = string.ascii_letters
    alphabet
    sentence = 'Jim quickly realized that the beautiful gowns are expensive'

Python maintain order in intersection of lists

This allows the list to be in the same order as the sentence. I use A as Alphabet and B as the list Hooray!!! Thanks Kasramvd but alas it only worked in the command line when I readjusted the order (ONCE). But gave me hope to keep pushing. As you can see I have commented out code in case I want to use it. I am using python3 canopy interface.

    a = sentence
    b = dict.fromkeys(a[i], 0)
    for i in a[i]:
        b[i] += 1


    #A = set(alphabet)
    #A = list(A)
    #B = set(sentence)

        #B = list(B)

    #maybe = set(B)&set(A)

    #letter_set = set(A) & set(B)

    letter_list = list(letter_set)

    common = sorted(set(A).intersection(set(B)) ,key=lambda x:B.index(x))

    letter_list = common #it is already a list

    count_letters = {}

    cnt_lowercase = 0

    cnt_uppercase = 0

    count = 0


    #iterate over the letter_list
    for i in range (len(letter_list)-1):
        #count matches for each letter of the sentence
        for j in range(len(sentence)-1):
            gr = letter_list[i] in sentence[j]
            print i,j
            print("sentence letter : " , letter_list[i], "sentence letter: " + sentence[j])

            print  gr 
            if gr == True:
                count +=1;
                if j == len(sentence)-1:
                    print("count= " , count)
                    count_letters[i] = count
            print(count_letters)
        if j > len(sentence):
            print("reached the last letter of the sentence: " , sentence[j])
            count = 0
    print j
    print ("length of the sentence is : " , len(sentence))
    print count_letters
    print letter_list

    common = sorted(set(A).intersection(set(B)) ,key=lambda x:B.index(x)) 

so this basically still is set(A) & set(B)

Any ideas??? I am too stubborn to let this go, after this I simply will turn it into a function so I can answer the next question as that is required for a much larger string of over 5 lines. I probably will be back if I get stuck again.

hope there was enough information.

Harry
  • 23
  • 7
  • We can't see the link if we don't have an edx account. If I understand you want to convert a string to a dictionary with letter as keys an number of occurrences as values. – EdKenbers Jun 19 '20 at 21:39
  • I think you can sort (in the order specified) the letters in your sentence and after that apply your script. – EdKenbers Jun 19 '20 at 21:45
  • 1
    I believe after python3.7 all dictionaries will remain ordered even without using collections.OrderedDict...so the issue is that you're defining the counts in the order the letters are appearing... as @Ed.Kenbers, just make sure the letters are sorted alphabetically before applying your code...or reorder it after the fact – Derek Eden Jun 19 '20 at 21:50
  • 1
    @Ed.Kenbers the question from the edx questionnaire is the following: Consider the sentence 'Jim quickly realized that the beautiful gowns are expensive'. Create a dictionary count_letters with keys consisting of each unique letter in the sentence and values consisting of the number of times each letter is used in this sentence. Count upper case and lower case letters separately in the dictionary. – Harry Jun 20 '20 at 13:41
  • @Derek Eden what method would I use to create the required order of my set of unique letters in the sentence being the same as the order of the letters in the sentence? As you can see I have not managed to get very far in my attempts. – Harry Jun 20 '20 at 13:44
  • @Ed.Kenbers the same comment was to you but was not able to tag the both of you – Harry Jun 20 '20 at 13:44

5 Answers5

1

Dictionaries are unordered collection of items in the form of key:value pairs. I have done the problem as:

d={}
s="Jim quickly realized that the beautiful gowns are expensive"
for i in s:
    d[i]=s.count(i)
print(d)

I have created an empty dictionary d and stored the string in variable s. Then I have used the for loop taking each element of the string s in i and then adding the key value pairs by assigning values to the keys: dict_name[key]=value. The values are added by the string method string_var.count(element): it counts the number of times an element occurs in the string_var. This way all the key:value pairs get added in the empty dictionary.

This prints the desired output:

{'J': 1, 'i': 5, 'm': 1, ' ': 8, 'q': 1, 'u': 3, 'c': 1, 'k': 1, 'l': 3, 'y': 1, 'r': 2, 'e': 8, 'a': 4, 'z': 1, 'd': 1, 't': 4, 'h': 2, 'b': 1, 'f': 1, 'g': 1, 'o': 1, 'w': 1, 'n': 2, 's': 2, 'x': 1, 'p': 1, 'v': 1}

Hope it was helpful!

Anshika Singh
  • 994
  • 12
  • 20
  • thankyou, This is even more helpful for my learning to get better at pyhon, I realised that the initial attempt was correct, not sure why I did not get it to work, I should have just done set(A) & set(B) and then put them in keys right? Your technique is something that will help me remember for the future – Harry Jun 20 '20 at 13:54
  • Yea! Thank you! I'm glad I could help! – Anshika Singh Jun 21 '20 at 07:37
  • I am not sure why but I am getting this output using your code, do you know why? {' ': 8, 'J': 1, 'a': 4, 'c': 1, 'b': 1, 'e': 8, 'd': 1, 'g': 1, 'f': 1, 'i': 5, 'h': 2, 'k': 1, 'm': 1, 'l': 3, 'o': 1, 'n': 2, 'q': 1, 'p': 1, 's': 2, 'r': 2, 'u': 3, 't': 4, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1} – Harry Jun 22 '20 at 12:40
  • And I would need to negate the space character so I think I need an if statemet for that right? – Harry Jun 22 '20 at 12:41
  • Yes if would solve it. And I'm sorry I don't know why your output differs from mine, I just ran my code again and the output is : `{'J': 1, 'i': 5, 'm': 1, ' ': 8, 'q': 1, 'u': 3, 'c': 1, 'k': 1, 'l': 3, 'y': 1, 'r': 2, 'e': 8, 'a': 4, 'z': 1, 'd': 1, 't': 4, 'h': 2, 'b': 1, 'f': 1, 'g': 1, 'o': 1, 'w': 1, 'n': 2, 's': 2, 'x': 1, 'p': 1, 'v': 1} ` – Anshika Singh Jun 22 '20 at 16:15
  • maybe my laptop or software likes to make things difficult for me, it might have the extra intelligent software added to it with experimental emotion evoking of the user to get partially confused :p – Harry Jun 23 '20 at 17:50
1

I think the correct code is:

s="Jim quickly realized that the beautiful gowns are expensive"
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(dict([[i, s.count(i)] for i in s if i in alphabet]))

So, whithout blanks, you'll get 1 for the 3rd value of the dictionary and 3 for the 8th. The output is:

{
    'J': 1, 'i': 5, 'm': 1, 'q': 1, 'u': 3, 'c': 1, 'k': 1, 'l': 3, 
    'y': 1, 'r': 2, 'e': 8, 'a': 4, 'z': 1, 'd': 1, 't': 4, 'h': 2, 
    'b': 1, 'f': 1, 'g': 1, 'o': 1, 'w': 1, 'n': 2, 's': 2, 'x': 1, 
    'p': 1, 'v': 1
}
jottbe
  • 4,228
  • 1
  • 15
  • 31
Jimmy Five
  • 11
  • 1
0

I think the easiest way to do this would be to just use the Counter function then sort after the fact like this:

from collections import Counter
sentence = 'Jim quickly realized that the beautiful gowns are expensive'
counts = Counter(sentence)
out = dict(sorted(counts.items()))

output:

{' ': 8, 'J': 1, 'a': 4, 'b': 1, 'c': 1, 'd': 1, 'e': 8, 'f': 1, 'g': 1, 'h': 2, 'i': 5, 'k': 1, 'l': 3, 'm': 1, 'n': 2, 'o': 1, 'p': 1, 'q': 1, 'r': 2, 's': 2, 't': 4, 'u': 3, 'v': 1, 'w': 1, 'x': 1, 'y': 1, 'z': 1}

I think this achieves what you want but as mentioned in the comments, we can't see the actual question. Let me know if this works or you need further help.

Derek Eden
  • 4,403
  • 3
  • 18
  • 31
  • this is good and is what I initially tried ... but thanks to you, I now realize that is the answer to the question :D I did not see it before, I had that result from before, but I don't remember it working. – Harry Jun 20 '20 at 13:52
  • I just realised looking at the question again that this won't work because the answer to the 8th dictionary object is meant to be 3. – Harry Jun 22 '20 at 12:35
0

I just checked the show answer after realising that option, here it is:

for letter in sentence:
    if letter in alphabet:
        if letter in count_letters.keys():
            count_letters[letter] += 1
        else:
            count_letters[letter] = 1
            
print(list(count_letters.values())[2])

1

print(list(count_letters.values())[7])

3

print(count_letters)

{'J': 1, 'a': 4, 'c': 1, 'b': 1, 'e': 8, 'd': 1, 'g': 1, 'f': 1, 'i': 5, 'h': 2, 'k': 1, 'm': 1, 'l': 3, 'o': 1, 'n': 2, 'q': 1, 'p': 1, 's': 2, 'r': 2, 'u': 3, 't': 4, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1}

hmmm.... its a shame shorter answers don't work but I guess it assumes no prior functions which is still good. And I misunderstood the question thinking I need Jim order. I need to understand the steps of this program now, as just having the answer will not be sufficient as I am trying to figure out now where it realises that count_letters.keys() has information when it was initially declared as empty... what is happening there for it to detect it has the data required.

Harry
  • 23
  • 7
0

I have added comments and print statements for me to see and understand why that code works the way it is meant to and hopefully it will help someone else

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
for letter in sentence:
    print ("letter in sentence is: ", letter) 
    if letter in alphabet: # so if there are spaces they will not be included into the dictionary
        print ("letter in alphabet is: ", letter) 
        if letter in count_letters.keys(): #becuase it has found a letter in both the sentence and alphabet in the first finding
            count_letters[letter] += 1
            print ("count_letters[letter] is: ",count_letters[letter])
            print ("letter is: " , letter)
        else:
            count_letters[letter] = 1
            print ("count_letters[letter] is: ",count_letters[letter])
            print ("letter is: " , letter)
    else: # this will help me realise when that happens
         print ("letter: ")
         print (letter)
         print("not in alphabet")
print(count_letters)            
print(list(count_letters.values())[2])
print(list(count_letters.values())[7])
Harry
  • 23
  • 7