Home > Net >  to collect in a list all that has the same count of items in the list and to creat a dictionary with
to collect in a list all that has the same count of items in the list and to creat a dictionary with

Time:01-02

For a given list of words such as

meyveler=["elma","armut","şeftali","kiraz","muz","erik","üzüm","nar","karpuz","kavun","kivi","havuç","portakal","mandalina"] 

I want to create a dictionary that displays words with equal letter numbers in the same groups, as in the example output below.

{ 3:['muz','nar'], 4: [‘kivi’,'elma','erik','üzüm' ] 5: [‘havuç’, 'armut','kiraz','kavun'] 6: [‘karpuz’], 7: [‘şeftali’], 8: [‘portakal’], 9: [‘mandalina’] }

Here is a code snippet that shows what I've tried so far:

n={}
t=set()
for i in meyveler:
    t.add(len(i))
p=list(t)
for i in meyveler:
    q=0
    while q<len(p):
        if len(i)==p[q]:
            n.update({p[q]:[i]})
        q =1
print(n)

CodePudding user response:

The code can be substantially simplified -- this snippet reads in one word at a time and inserts it into the appropriate list (creating new key-value pairs if a word has a length we haven't seen at that point):

meyveler=["elma","armut","şeftali","kiraz","muz","erik","üzüm","nar","karpuz","kavun","kivi","havuç","portakal","mandalina"] 
n = {}
for word in meyveler:
    if len(word) not in n:
        n[len(word)] = []
    n[len(word)].append(word)
    
print(n)

CodePudding user response:

I think you are making things a little more complex that you need to. Just loop through the set of words and append to the list (or create the list if you haven't seen the count yet). setdefault() is handy for this. You could also use collections.defaultdict.

meyveler=["elma","armut","şeftali","kiraz","muz","erik","üzüm","nar","karpuz","kavun","kivi","havuç","portakal","mandalina"] 

counts = {}
for word in set(meyveler):
    counts.setdefault(len(word), []).append(word)

print(counts)
# {7: ['şeftali'], 4: ['elma', 'üzüm', 'kivi', 'erik'], 5: ['havuç', 'kavun', 'armut', 'kiraz'], 3: ['nar', 'muz'], 8: ['portakal'], 6: ['karpuz'], 9: ['mandalina']}

Edit:
I am passing the original list to set() because I saw your use of set() and thought you might be concerned about duplicates. As the comments mention, you could use sets instead of lists in the dictionary (counts.setdefault(len(word), set())). Or, if you're not concerned with duplicates, just iterate over the list (for word in meyveler: ...).

CodePudding user response:

Your code doesn't produce your desired dictionary because in every iteration, you are updating n instead of adding to its values. If you replace

n.update({p[q]:[i]})

with

n[p[q]] = n.get(p[q], [])   [i]

your code will work as expected. But as the other answers suggest, it's far better to iterate over meyveler once and decide on the spot where to place the word in n depending on its length, instead using 2 iterations (or in your case double iterations). That's why it's a better solution to use methods like collections.defaultdict or dict.setdefault or dict.get where you can set a default value (such as empty lists) for keys yet to be defined and just append to them.

Here's one way:

from collections import defaultdict
n = defaultdict(list)
for w in meyveler:
    n[len(w)].append(w)

Here's another (this method finds the lengths and them iterates over the list again similar to your method but you'll find that this is slower than the other methods):

n = {}
for length, word in zip(map(len, meyveler), meyveler):
    n[length] = n.get(length, [])   [word]

Output:

{4: ['elma', 'erik', 'üzüm', 'kivi'],
 5: ['armut', 'kiraz', 'kavun', 'havuç'],
 7: ['şeftali'],
 3: ['muz', 'nar'],
 6: ['karpuz'],
 8: ['portakal'],
 9: ['mandalina']}
  • Related