Saturday, 15 March 2014

python - Creating a dictionary with nested arrays -



python - Creating a dictionary with nested arrays -

how take pre-existing dictionary , add together item list dictionary tuple using loop? made illustration below. want take color_dict , reformat each item in format 'r':['red',1].

i got far below, couldn't figure out how lastly part.

lista = {'red':'r', 'orange':'o', 'yellow':'y', 'green':'g', 'blue':'b', 'indigo':'i', 'violet':'v'} color_dict = {'r':1, 'o':2, 'y':3, 'g':4, 'b':5, 'i':6, 'v':7} = color_dict.keys() color_keys = [] color_vals = [] x in lista[0::2]: color_keys.append(x) x in lista[1::2]: color_vals.append(x) new = zip(color_keys, color_vals) new_dict = dict(new) print new_dict

if has other suggestions great, i'm not understanding how utilize dict comprehension.

basically want loop through items in lista , each pair color: colkey find respective value in color_dict (indexed colkey). , need stitch together: colkey: [color, color_dict[colkey]] new item in new dict each item in lista dict.

you can utilize dict comprehension build this:

>>> new_dict = {colkey: [color, color_dict[colkey]] color, colkey in lista.items()} >>> new_dict {'o': ['orange', 2], 'y': ['yellow', 3], 'v': ['violet', 7], 'r': ['red', 1], 'g': ['green', 4], 'b': ['blue', 5], 'i': ['indigo', 6]}

python

No comments:

Post a Comment