This function allows you to do exactly that, and gives you the choice of integer keys or letter keys by typing int
or chr
as the third function argument:
def ds(d,n,v=chr):
return({v(int(y/n)+[96 if v==chr else 0][0]):"".join([str(d[z]) for z in d])[y-n:y] for y in range(n,len("".join([d[z] for z in d]))+n,n)})
This works by first iterating through the dictionary values and returning the value of each key (in the str(d[z]) for z in d
). The function then joins the list of string values together, (the "".join part), and then parses through the length that string (the for y in range(...)
part) and returns a dictionary with values split every n
th time.
Examples:
a=ds(myDictionary,2) #split every second character (string keys)
print(a)
#{'a': 'qw', 'b': 'er', 'c': 'ty', 'd': 'ui', 'e': 'op'}
b=ds(myDictionary,3,int) #split every third (integer keys)
print(b)
#{1: 'qwe', 2: 'rty', 3: 'uio', 4: 'p'}
c=ds(myDictionary,56,char) #split every fifty-sixth (string keys)
print(c)
#{'a': 'qwertyuiop'}
Also, no outside modules required! This is all built-in stuff.