How can I add multiple keys to a python Dictionary?

时间:2017-04-10 01:04:20

标签: python dictionary web-scraping data-analysis

I have a web scraper that grabs info and saves it to a database. I use the following code to save data.

try: 
    base['vevo']['url']
except:
    base['vevo']['url'] = "NotGiven"
try: 
    base['vevo']['viewsLastWeek']['data']['time']
except:
    base['vevo']['viewsLastWeek']['data']['time'] = '2199-01-01'

Now normally this works, however ocassionally the data stream doesn't return any info at all for base['vevo']. This breaks the above dict add and says that KeyError 'vevo'.

I've been trolling through other stackoverflow questions, but I haven't been able to find anything that references adding multiple keys at once like I'm trying to do. I've tried to use base.append('key'), tried base.get() but couldn't find a reference on how to use it for multiple keys deep. Any ideas on how to get around it?

2 个答案:

答案 0 :(得分:1)

You can use defaultdict.

import collections
def new_level():
    return collections.defaultdict(new_level)
base=new_level()

This would allow you to add an arbitrary number of levels to your nested dicts:

 >>> base["foo"]["bar"]["foobar"]=42
 {'foo': {'bar': {'foobar': 42}}}

答案 1 :(得分:0)

所以我找到了一个解决方案,但它涉及逻辑上的改变而不是我最初尝试做的事情。

由于我只使用字典值保存到我的数据库,因此我可以使用占位符变量作为函数的中间值。请参阅下面的工作代码..

try: 
    v_url = base['vevo']['url']
except:
    v_url = "NotGiven"

向现有字典添加值证明过于复杂,此解决方案不涉及额外的包。