F
F
fantom_ask2020-05-08 20:21:47
Python
fantom_ask, 2020-05-08 20:21:47

How to iterate over a dictionary if there are fewer available indexs than necessary?

I decided to try to create a color iteration function
The number of elements inside the dictionary can be different, as well as the number in num

If the number of elements is greater than the number num, then the remainder is not taken into account
1:red, 2:blue, 3:green # The rest is removed :yellow , :brown

If the number elements less than the number num then

Either the values ​​are sorted through the second circle
1:red, 2:blue, 3:green, 4:red, 5:blue,

Or the last available number is set

1:red, 2:blue, 3:green, 4:green, 5:green,
1:red, 2:blue, 3:green, 4:blue, 5:green,


The step value affects the order of output
where only every second element of the list is taken into account every third and so on

My code
from collections import defaultdict

arr = {
  'A_text':['Blue','Green'],
  'background':['Putpure','Brown','White',"Lemon"],
  'border':['Yellow','Sky'],
  'shadow':['Pink','Black'],
}
#arr = {'A_text':['Blue','Green']}
step = [2,1]
type = [1]

def fun(
    id,
    child=None,
    type=3, 
    num=1 
  ):
  end = 0 if type == 1 else len(child)-1 if  type == 2 else id
  #print('{}+{}'.format(id+num,len(child)-1))
  if id+num <= len(child)-1 :
    #print("BAD")
    fin = id+num 
  else :
    fin = end
  #print('fin {}'.format(fin))
  return fin
  #return id+num if id+num <= len(child)-1 else end

num = 3
id = defaultdict(int)
for x in range(num):
  new_arr = {}
  for key, value in sorted(arr.items()):
    #print(arr[key])
    #print(id[key])
    #print(id['step'])
    #print(id['type'])
    if key == 'A_text' :
      new_arr[key] = [
        arr[key][id[key]],
        arr[key][fun(id[key], arr[key] ,1, 1)]
      ]
    else :
      new_arr[key] = arr[key][id[key]]
    id[key] = fun(
      id[key],
      value,
      type[id['type']],
      step[id['step']]
    )
    id['step'] = fun(id['step'],step)
    id['type'] = fun(id['type'],type)
  print(new_arr)


Now I'm confused and don't quite understand why
A_text after the second value instead of ['Blue','Green'] outputs ['Green','Blue']

Yes, I know how terrible it all looks.

But if anyone knows how to display the values ​​if the available indexs is less than num,
then you can answer me

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey, 2020-05-09
@mrkaban

please forgive me for not delving into the code, but why can't you iterate over the dictionary in the usual way?
for key in arr.keys():
print(key)
or
for key in arr:
print(key)

F
fantom_ask, 2020-05-09
@fantom_ask

I seem to be able to solve the problem by adding

for x in range(num):
  new_arr = {}
  id['step'] = 0
  id['type'] = 0
  for key, value in sorted(arr.items()):

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question