1

In this function, I am trying to create a list which includes the keys of a dictionary multiplied by the value they are mapped to, value being a non-negative integer. My code gives me what I am looking for but treats every character of the keys(which are strings) as individual and not as one string, i.e. {'APPLE': 2} --> ['A', 'P', 'P', 'L', 'E', 'A', 'P', 'P', 'L', 'E'] and not ['APPLE', 'APPLE'] Here is my code:

def flatten_dict(d):
    flattened_dict = []
    for key in d:
        flattened_dict += flatten_lists(key)*d[key]
    return flattened_dict

Thank you for all help

5 Answers5

1

You want to walk through all dictionary key-value pairs and append each key value times to the new list. dict.items() is a nice way to make this a bit more concise too.

flattened_list = []

for k,v in d.items():
    for _ in range(v):
        flattened_list.append(k)
Antimon
  • 597
  • 3
  • 10
0

You are currently having the key on a word level, you need to flatten the keys to character level first. One way to achieve that is to create a new dictionary/hashtable that counts the occurrence of each character in the word, then use your current code on that new dictionary.

Phi
  • 1
  • 1
0

This should help, instead of multiplying, which would concatenate the string, i iterated over the number:

flattenset = {'APPLE': 2, 'WHAT': 3}
flattenlist = []
for item in flattenset:
  for x in range(flattenset[item]):
    flattenlist.append(item)
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
0

If i understand you correctly, then this code will put the keys of your dicionary value times into a list.

def flatten_dict(d):
    flattened_dict = []
    for key, value in d.items():
        flattened_dict.extend([key for _ in range(value)])
    return flattened_dict


print(flatten_dict({"Apple": 2,
                    "Pear": 3,
                    "Nuts": 0}))

Outputs: ['Apple', 'Apple', 'Pear', 'Pear', 'Pear']

Dudly01
  • 444
  • 3
  • 13
0

Here is a single line answer using list comprehension:

a = {'APPLE':2, "Orange": 3}

# extract the key and values from a.items() and then repeat it 'n' times
output = [key for key, value in a.items() for n in range(value)]

output

This returns:

['APPLE', 'APPLE', 'Orange', 'Orange', 'Orange']

To break down the comprehension: This extracts each key, value pair from the dictionary and returns the key

key for key, value in a.items()

And then we repeat the key by value times

for n in range(value)

Note: n is not really used and can even be replaced by _ to indicate a throw away value.

razdi
  • 1,388
  • 15
  • 21