0

Hi, Can you give me a tip about how i print counted letters in input's order? The code in this post print them randomly

text = input() mydict = {} letters = [a for a in text] mydict = dict((i, letters.count(i)) for i in set(letters)) print(mydict)

11th Jul 2022, 2:18 AM
Arif Şhn
Arif Şhn - avatar
7 Réponses
+ 6
Arif Şhn The text variable will produce a string which may be iterated upon directly. You won't need to worry about duplicate items in the dict, because each key is unique. text = input() mydict = dict((i, text.count(i)) for i in text) print(mydict)
11th Jul 2022, 5:00 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
Arif Şhn Use list instead of set because set will replace previous value with next value so suppose input is "anant" so set will give ['n', 'a', 't']
11th Jul 2022, 3:05 AM
A͢J
A͢J - avatar
+ 3
Thank you both🙏
11th Jul 2022, 5:23 AM
Arif Şhn
Arif Şhn - avatar
+ 2
A͢J Isn't the order of elements random every time with a set? I don't understand.
11th Jul 2022, 6:22 AM
Korkunç el Gato
Korkunç el Gato - avatar
+ 2
Korkunç el Gato you are right! Even if the text provided by user has unique characters (not repeating chars as set() will remove them), it will print them randomly. I am not sure how it works though.
11th Jul 2022, 6:58 AM
Sandeep
Sandeep - avatar
+ 2
Korkunç el Gato i am not sure if it is always the case but doing set(a) will return a set with item sorted (tried with numbers). Therefore, maybe it's not random. Note: Here, a is list containing duplicate random chars.
11th Jul 2022, 5:27 PM
Sandeep
Sandeep - avatar
+ 1
Thanks for removing the confusion Sandeep.
11th Jul 2022, 5:07 PM
Korkunç el Gato
Korkunç el Gato - avatar