嵌套字典中的Python set-item与路径

时间:2014-09-16 20:05:05

标签: python

假设有一个带有各种信息的嵌套字典(如下所示)。我总是有一种方法来存储直接相关项的路径,但不是将数据存储到原始字典的好方法(因为与数组不同的字母不会简单地指向对象的存储空间)。

sample_dict = 
{ 'title': <book_title>,
  'author': {'first_name': <first_name>, 'last_name': <last_name>, 'date_of_birth':<date of birth>},
 'publisher': {'publisher_name': <publisher_name>, 'contact_info': {'address': <address>, 'email': <email>}}
} (or etc) 

也就是说,使用类似的路径(检索发布者电子邮件):

publisher_email_path = 'publisher.contact_info.email' 
temp_dict=sample_dict
for node in publisher_email_path.split('.'): 
  temp_dict = temp_dict.get(node)

但是存储新的(例如发布商电子邮件)的相反方法将不起作用,因为:

for node in publisher_email_path.split('.')[:-1]: 
    temp_dict = temp_dict.get(node)
temp_dict['email'] = <new_email> 

只会更新temp_dict,而不会更新原始文件。一个选项似乎是递归地更新每个子字典从最小的开始到最顶端 - 但这看起来很难看。 理想情况下,人们可以为路径中的每个节点执行sample_dict [node [node [node]]] - 但我不确定是否有解决方案来复制&#39; [&#39; &#39;]&#39;括号。

2 个答案:

答案 0 :(得分:2)

您的程序中有几个语法错误和一个逻辑错误。

逻辑错误是您使用sample_dict。你有

for ...:
   temp_dict = sample_dict.get(...)

应该是

temp_dict = sample_dict
for ...:
   temp_dict = temp_dict.get(...)

以下是您的示例的固定版本。请注意temp_dict循环中for的使用。

sample_dict = {
    'title': '<book_title>',
  'author': {'first_name': '<first_name>', 'last_name': '<last_name>', 'date_of_birth':'<date of birth>'},
 'publisher': {'publisher_name': '<publisher_name>', 'contact_info': {'address': '<address>', 'email': '<email>'}}
}

publisher_email_path = 'publisher.contact_info.email'
temp_dict=sample_dict
for node in publisher_email_path.split('.'):
  temp_dict = temp_dict.get(node)
print temp_dict  # prints '<email>'


temp_dict = sample_dict
for node in publisher_email_path.split('.')[:-1]:
    temp_dict = temp_dict.get(node)
temp_dict['email'] = '<new_email> '

publisher_email_path = 'publisher.contact_info.email'
temp_dict=sample_dict
for node in publisher_email_path.split('.'):
  temp_dict = temp_dict.get(node)
print temp_dict  # prints '<new_email>'

顺便说一句,您还可以使用for函数表达reduce循环:

publisher_email_path = 'publisher.contact_info.email'.split('.')
print reduce(dict.get, publisher_email_path, sample_dict)

答案 1 :(得分:0)

嗯...你声称​​不的工作,实际上 ,至少在python 2.7中:

>>> d = {1:{2:''}}
>>> d2 = d[1]
>>> d
{1: {2: ''}}
>>> d2
{2: ''}
>>> d2[3]=4
>>> d
{1: {2: '', 3: 4}}
>>> d2
{2: '', 3: 4}