0
dict={a:qwertyuiop} dict1={a:qw,b:er,c:ty,d:ui,e:op}

I want to create dict 1 from dict with splitting the value with length of 2

I have tried

value1=dict.value()
value2=value1.split(2)

It does not accept integer and I obviously using the wrong function, I have searched on the net but could not find it, which function should I use?

2 Answers2

0
# Defining variables
d = {'a': 'abcde', 'b': 'cdefghi'}
n = 2

# One-Liner:
d1 = dict([(i + j*len(d), word) for j, key in enumerate(d.keys()) for i, word in enumerate([d[key][i:i+n] for i in range(0, len(d[key]), n)])])
print(d1)

# Normal code
d2 = dict()
for j, key in enumerate(d.keys()):  # Enumerating threw the keys
    for i, word in enumerate([d[key][i:i + n] for i in range(0, len(d[key]), n)]):  # Enumerating threw n-characters at a time
        d2[i + j*len(d)] = word  # Assigning to the right key with math
print(d2)

One downside to this code is that we are losing the keys, This has to be done in order to keep having only one key per value.

Output for d1: {0: 'ab', 1: 'cd', 2: 'cd', 3: 'ef', 4: 'gh', 5: 'i'}

Output for d2: {0: 'ab', 1: 'cd', 2: 'cd', 3: 'ef', 4: 'gh', 5: 'i'}

Eilonlif
  • 346
  • 2
  • 7
0

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 nth 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.

Agent Biscutt
  • 712
  • 4
  • 17