-3

I have an array a that I want to store every 5 values of in a dictionary, while programmatically creating keys.

For example:

if we have

a=[1,2,3,4,5,6,7,8,9,10]

I want the dictionary to look like this:

d={"first_title":[1,2,3,4,5], "second_title":[6,7,8,9,10]}

Edit: I have thousands of terms so I want to do this in a loop

BobelLegend
  • 91
  • 2
  • 10
  • 1
    How do you envision "programmatically creating keys"? – Prune Aug 17 '18 at 17:53
  • 1
    `a` is a list, not an array. Slicing into regular chunks is handled in many other questions and other help sites. Where are you stuck on that part? – Prune Aug 17 '18 at 17:53
  • 1
    The `d` in your example is not a dictionary, it uses illegal notation. – DYZ Aug 17 '18 at 18:02

3 Answers3

3

Dictionary values can be any object, including arrays. So, you just start with an empty dict, and add array values to it.

my_dict = {}
year = 1984
for index in range(0, len(a), 5):
    my_dict[year] = a[index: index+5]
    year += 1
blue_note
  • 27,712
  • 9
  • 72
  • 90
2

A somewhat general and pythonic solution is the following:

from itertools import izip_longest


def grouper(n, iterable, fillvalue=None):
    """grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"""
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

keys = ["first-title", "second-title"]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

result = {key: list(group) for key, group in zip(keys, grouper(5, a))}

This uses the grouper recipe (see this answer for a better explanation). A less pythonic solution, is to iterate over the pair of keys and groups using a for loop:

result = {}
for key, group in zip(keys, grouper(5, a)):
    result[key] = group

In both cases the output is:

{'first-title': [1, 2, 3, 4, 5], 'second-title': [6, 7, 8, 9, 10]}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
2

How about this?

Input:

a = [1,2,3,4,5,6,7,8,9,10]
keys = [1984, 1985, 1986, 1987] 
n = 5

Code:

my_dict = {}

for i in range(len(a)//n):
    key = str(keys[i]) if i < len(keys) else "after " + str(keys[-1])
    my_dict[key] = a[i*n: (i+1)*n]

print(my_dict)

Output:

{'1984': [1, 2, 3, 4, 5], '1985': [6, 7, 8, 9, 10]}

Depending on your use case you could also do something like this:

# Input
a = range(22)
keys = [1984, 1985, 1986] # maybe replace it with range(1984, 2000)
n = 5

# Code
b = a
my_dict = {}

for i in range(min(len(keys), len(a)//n)):
    key = keys[min(i, len(keys)-1)]
    my_dict[key] = b[:n]
    b = b[n:]

my_dict['later'] = b

print(my_dict)

# Output
{
    1984: [0, 1, 2, 3, 4], 
    1985: [5, 6, 7, 8, 9], 
    1986: [10, 11, 12, 13, 14], 
    'later': [15, 16, 17, 18, 19, 20, 21]
}
Fabian N.
  • 3,807
  • 2
  • 23
  • 46