简体   繁体   中英

How to do two-level nested map

This is my code:

html_tags = [{'tag': 'a',
              'attribs': [('class', 'anchor'),
                          ('aria-hidden', 'true')]}]

I just can do it by one-level for-loop and one-level map as follow:

for index, tag in enumerate(html_tags):
    html_tags[index]['attribs'] = map(lambda x: '@{}="{}"'.format(*x), tag['attribs'])
print html_tags

However, this is my output (result):

[{'attribs': ['@class="anchor"', '@aria-hidden="true"'], 'tag': 'a'}]

How to do two-level nested map and output the same result.

I suggest a dictionary comprehension :

>>> html_tags = [{i:map(lambda x: '@{}="{}"'.format(*x), j) if i=='attribs' else j for i,j in html_tags[0].items()}]
>>> html_tags
[{'attribs': ['@class="anchor"', '@aria-hidden="true"'], 'tag': 'a'}]
>>> 

Also instead of using map with lambda as a more efficient way you can use a list comprehension :

>>> html_tags = [{i:['@{}="{}"'.format(*x) for x in j] if i=='attribs' else j for i,j in html_tags[0].items()}]
>>> html_tags
[{'attribs': ['@class="anchor"', '@aria-hidden="true"'], 'tag': 'a'}]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM