iterate through python dictionary and special append to new list?

  • Last Update :
  • Techknowledgy :

The culprit:

for range in (value):
   freq_lst.append(value)

The rescuer:

for i in range(value):
   freq_lst.append(key)

Hence:

def get_freq_dict():
   freq_dict = {
      'J': 1,
      'K': 1,
      'Q': 1,
      'X': 1,
      'Z': 1,
      \
      'B': 2,
      'C': 2,
      'F': 2,
      'H': 2,
      'M': 2,
      'P': 2,
      \
      'V': 2,
      'W': 2,
      'Y': 2,
      '': 2,
      \
      'G': 3,
      'D': 4,
      'L': 4,
      'S': 4,
      'U': 4,
      \
      'N': 6,
      'R': 6,
      'T': 6,
      'O': 8,
      'A': 9,
      'I': 9,
      \
      'E': 12
   }
return freq_dict

def bag_of_letters(freq_dict):
   freq_lst = []
for key, value in freq_dict.items():
   # print(key, value)
for i in range(value):
   freq_lst.append(key)
return freq_lst

def main():

   freq_dict = get_freq_dict()
freq_lst = bag_of_letters(freq_dict)

print(freq_lst)
main()

if you want them nicely paired:

 for i in range(value):
    freq_lst.append([key] * value)

Ans: Because you're printing both the dict and the list:

print(freq_dict, freq_lst)

Here you are

freq_dict = {
   'J': 1,
   'K': 1,
   'Q': 1,
   'X': 1,
   'Z': 1,
   \
   'B': 2,
   'C': 2,
   'F': 2,
   'H': 2,
   'M': 2,
   'P': 2,
   \
   'V': 2,
   'W': 2,
   'Y': 2,
   '': 2,
   \
   'G': 3,
   'D': 4,
   'L': 4,
   'S': 4,
   'U': 4,
   \
   'N': 6,
   'R': 6,
   'T': 6,
   'O': 8,
   'A': 9,
   'I': 9,
   \
   'E': 12
}

def bag_of_letters():
   freq_lst = []

for key in freq_dict:
   for i in range(0, freq_dict[key]):
   freq_lst.append(key)

return freq_lst

def main():
   freq_lst = bag_of_letters()
print(freq_lst)

main()

You should iterate through a range instead, and append key rather than value:

for key, value in freq_dict.items():
   for _ in range(value):
   freq_lst.append(key)

Alternatively, you can use a list comprehension:

def bag_of_letters(freq_dict):
   return [i
      for k, v in freq_dict.items() for i in [k] * v
   ]

as shown in this topic, therefore you might just do:

import itertools
x = {
   'A': 1,
   'B': 2
}
out = list(map(lambda x, y: [x] * y, x.keys(), x.values()))
print(out) #[['A'], ['B', 'B']]
out = list(itertools.chain.from_iterable(out))
print(out) #['A', 'B', 'B']

I used itertools to flatten list, if you do not wish to import itertools you might do:

out = sum(out, [])

instead of

out = list(itertools.chain.from_iterable(out))

You can easily do it with Counter:

from collections
import Counter

d = {
   'C': 3,
   'B': 2,
   'A': 1
}
c = Counter(d)
list(c.elements())
#['C', 'C', 'C', 'B', 'B', 'A']

Suggestion : 2

Iterate over a dictionary with list values using nested for loop.,We iterated over all key value pairs using list comprehension, then for each value (list object), we iterated over all the items in that list too and created a list of key-value pairs.,First, we will iterate over all the items (key-value pairs) of dictionary by applying a for loop over the sequence returned by items() function. As value field of a key-value pair can be a list, so we will check the type of value for each pair. If value is list then iterate over all its items using an another for loop and print it, otherwise just print the value. For example,,Iterate over a dictionary with list values using list comprehension.

Suppose we have a dictionary with list as values for most of the keys. It means multiple values are associated with some keys,

# Create a dictionary where multiple values are
# associated with a key
word_freq = {
   'is': [1, 3, 4, 8, 10],
   'at': [3, 10, 15, 7, 9],
   'test': 33,
   'this': [2, 3, 5, 6, 11],
   'why': [10, 3, 9, 8, 12]
}
2._
# Create a dictionary where multiple values are
# associated with a key
word_freq = {
   'is': [1, 3, 4, 8, 10],
   'at': [3, 10, 15, 7, 9],
   'test': 33,
   'this': [2, 3, 5, 6, 11],
   'why': [10, 3, 9, 8, 12]
}

# Iterate over a dictionary with list values using nested
for loop
for key, values in word_freq.items():
   print('Key :: ', key)
if (isinstance(values, list)):
   for value in values:
   print(value)
else:
   print(value)

Output:

Key::is
1
3
4
8
10
Key::at
3
10
15
7
9
Key::test
9
Key::this
2
3
5
6
11
Key::why
10
3
9
8
12

Suggestion : 3

July 10, 2021July 10, 2021

1._
dicts = {}

keys = [10, 12, 14, 16]
values = ["A", "B", "C", "D"]

for i in range(len(keys)):
   dicts[keys[i]] = values[i]
print(dicts)

Auto-assign key in range with the given value

dicts = {}
keys = range(4)
values = ["A", "B", "C", "D"]
for i in keys:
   dicts[i] = values[i]
print(dicts)

Appending values to dictionary in for loop

dicts = {
   0: 'A',
   0: 'B'
}
keys = [10, 12]
values = ["A", "B"]

for i in range(len(keys)):
   dicts[keys[i]] = values[i]
print(dicts)