Python build one dictionary from a list of keys, and a list of lists of values -
so have list of keys:
keys = ['id','name', 'date', 'size', 'actions']
and have list of lists of vales:
values= [ ['1','john','23-04-2015','0','action1'], ['2','jane','23-04-2015','1','action2'] ]
how can build dictionary keys matched values?
the output should be:
{ 'id':['1','2'], 'name':['john','jane'], 'date':['23-04-2015','23-04-2015'], 'size':['0','1'], 'actions':['action1','action2'] }
edit: tried use zip() , dict(), work if list of values had 1 list, i.e. values = [['1','john','23-04-2015','0','action1']]
for list in values: dic = dict(zip(keys,list))
i thought initialising dic keys, building list of values on own, felt there had easier way it.
dic = dict.fromkeys(keys) list in values: ids = list[0] names = list[1] dates = list[2] sizes = list[3] actions = list[4]
and
dic['id'] = ids dic['name'] = names dic['date'] = dates dic['size'] = sizes dic['action'] = actions
this seemed silly , wondering better way of doing be.
>>> keys = ['id','name', 'date', 'size', 'actions'] >>> values = [['1','john','23-04-2015','0','action1'], ['2','jane','23-04-2015','1','action2']] >>> c = {x:list(y) x,y in zip(keys, zip(*values))} >>> c {'id': ['1', '2'], 'size': ['0', '1'], 'actions': ['action1', 'action2'], 'date': ['23-04-2015', '23-04-2015'], 'name': ['john', 'jane']} >>> print(*(': '.join([item, ', '.join(c.get(item))]) item in sorted(c, key=lambda x: keys.index(x))), sep='\n') id: 1, 2 name: john, jane date: 23-04-2015, 23-04-2015 size: 0, 1 actions: action1, action2
this uses several tools:
c
created dictionary comprehension. comprehensions different way of expressing iterable dictionary or list. instead of initializing empty iterable , using loop add elements it, comprehension moves these syntactical structures around.
result = [2*num num in range(10) if num%2]
is equivalent to
result = [] num in range(10): if num%2: # shorthand "if num%2 results in non-zero", or "if num not divisible 2" result.append(2*num)
and [2, 6, 10, 14, 18]
.
zip()
creates generator of tuples, each element of each tuple corresponding element of 1 of arguments passed zip()
.
>>> list(zip(['a','b'], ['c','d'])) [('a', 'c'), ('b', 'd')]
zip()
takes multiple arguments - if pass 1 large list containing smaller sublists, result different:
>>> list(zip([['a','b'], ['c','d']])) [(['a', 'b'],), (['c', 'd'],)]
and not want. however, our values
list such list: large list containing sublists. want zip()
sublists. great time use *
operator.
the *
operator represents "unpacked" iterable.
>>> print(*[1,2,3]) 1 2 3 >>> print(1, 2, 3) 1 2 3
it used in function definitions:
>>> def func(*args): ... return args ... >>> func('a', 'b', []) ('a', 'b', [])
so, create dictionary, zip()
lists of values together, zip()
keys. iterate through each of tuples , create dictionary out of them, each tuple's first item being key , second item being value (cast list
instead of tuple
).
to print this, make large looping structure, or can make generators (quicker assemble , process full data structures list
) , iterate through them, making heavy use of *
unpack things. remember, in python 3, print
can accept multiple arguments, seen above.
we first sort dictionary, using each element's position in keys
key. if use key=len
, sends each element len()
function , uses returned length key. use lambda
define inline, unnamed function, takes argument x
, return
s x
's index in list
of keys
. note dictionary isn't sorted; we're setting can iterate through according sort order.
then can go through sorted dictionary , assemble elements printable strings. @ top level, join()
key value separated ': '
. each value has elements join()
ed ', '
. note if elements weren't strings, have turn them strings join()
work.
>>> list(map(str, [1,2,3])) ['1', '2', '3'] >>> print(*map(str, [1,2,3])) 1 2 3
the generator yield
s each of these join()
ed lines unpacked *
operator, , each element sent argument print()
, specifying separator of '\n'
(new line) instead of default ' '
(space).
it's fine use loops instead of comprehensions , *
, , rearrange them such structures after logic functional, if want. it's not particularly necessary of time. comprehensions execute faster equivalent loops, , practice may come prefer syntax of comprehensions. learn *
operator, though - it's enormously versatile tool defining functions. **
(often referred "double star" or "kwargs"), unpacks dictionaries keyword arguments , can used define functions.