3

I have a list d of 'tokens' all strings and a list of tuples of the form (fieldname,fieldtype) For Example

ds = ['1','1','1','1','1']
fs = [('type',str),('value',int),('hidden',bool),('length',int),('pieces',str)

and I want to make a dict v having the following form

v = {'type':'1','value',1,'hidden':True,'length':1,'pieces','1')

What I currently have is very inefficient (I map the type func in the tuple to elements in the list one at a time)

v = {}
for j in xrange(len(fs)):
    v[fs[j]] = map(fs[j][1],[ds[j]])[0]

How can I make this efficient and easy to read? I've tried lambdas, etc. If this were a one time thing I would just do it manually but there are multiple lists of tuples some of them 50 elements long.

1
  • Thanks all for below answers so promptly Commented Apr 17, 2014 at 17:17

3 Answers 3

4

You can zip() the lists and apply function defined in fs to the appropriate ds value:

>>> ds = ['1','1','1','1','1']
>>> fs = [('type',str),('value',int),('hidden',bool),('length',int),('pieces',str)]
>>> {key: f(value) for (key, f), value in zip(fs, ds)}
{'hidden': True, 'type': '1', 'length': 1, 'value': 1, 'pieces': '1'}
Sign up to request clarification or add additional context in comments.

Comments

1

I was thinking something along the lines of:

>>> items = iter(ds)
>>> v = {a: b(next(items)) for a, b in fs}
>>> v
{'type': '1', 'hidden': True, 'pieces': '1', 'length': 1, 'value': 1}

That is what I would probably do.

2 Comments

used as it seems most efficient, never even thought of a dict comprehension.
@dvp It is most efficient as you are only holding one item in memory at a time, but with zip you iterate twice unnecessarily. Glad I could help!
0

My idea (not much readable):

>>> v = {t[0]:t[1](ds[i]) for i,t in enumerate(fs)}
>>> v
{'hidden': True, 'type': '1', 'length': 1, 'value': 1, 'pieces': '1'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.