4

我正在寻求创建一个函数addproperty(property_str, property_dict, old_dict = None),您需要一个字符串、一个字典和一个可选字典作为参数。该函数需要返回一个新字典,其中相应的值被添加到可选字典中。

例如。如果我输入:

capitals_dict = {'USA': 'Washington', 'Russia': 'Moscow', 'Japan': 'Tokyo'}

该函数addproperty('capital', capitals_dict)需要返回以下字典

{'USA': {'capital': 'Washington'}, 'Russia': {'capital': 'Moscow'}, 'Japan': {'capital': 'Tokyo'}}

当我在可选参数中输入该字典时,我还需要能够扩展此类字典以向这些国家/地区添加新的详细信息。

例如:

old_dict = {'USA': {'capital': 'Washington'}, 'Russia': {'capital': 'Moscow'}, 'Japan': 'capital': 'Tokyo'}}
demonym_dict = {'USA': 'American', 'Russia': 'Russian', 'Japan': 'Japanese'}

然后addproperty('demonym', demonym_dict, old_dict)需要返回:

{'USA': {'capital': 'Washington', 'demonym': 'American'}, 'Russia': {'capital': 'Moscow', 'demonym': 'Russian'}, 'Japan': {'capital': 'Tokyo', 'demonym': 'Japanese'}}

我应该如何从这里开始?

4

3 回答 3

5
def addproperty(property_str, property_dict, old_dict=None):
    result = old_dict if old_dict is not None else {}
    for k, v in property_dict.items():
        result.setdefault(k, {})[property_str] = v
    return result

例如:

>>> capitals_dict = {'USA': 'Washington', 'Russia': 'Moscow', 'Japan': 'Tokyo'}
>>> result = addproperty('capital', capitals_dict)
>>> result
{'Japan': {'capital': 'Tokyo'}, 'Russia': {'capital': 'Moscow'}, 'USA': {'capital': 'Washington'}}
>>> demonym_dict = {'USA': 'American', 'Russia': 'Russian', 'Japan': 'Japanese'}
>>> addproperty('demonym', demonym_dict, result)
{'Japan': {'demonym': 'Japanese', 'capital': 'Tokyo'}, 'Russia': {'demonym': 'Russian', 'capital': 'Moscow'}, 'USA': {'demonym': 'American', 'capital': 'Washington'}}

请注意,old_dict如果提供,这将修改。如果这是一个问题,请导入复制模块并将函数中的第一行替换为以下内容:

result = copy.deepcopy(old_dict) if old_dict is not None else {}
于 2013-04-26T19:06:27.330 回答
2

我疯狂的单线解决方案:)

def addproperty(property_str, property_dict, old_dict = None):
    return {k: (lambda k, v: old_dict[k] if old_dict != None else { property_str: v})(k,v) for k, v in property_dict.items()}

返回新字典。

于 2013-04-26T19:34:43.200 回答
0

像这样的东西:

def add_property(item,dic,new_dic=None):
    if not new_dic:
        for k,v in dic.items():
            dic[k]={item:v}
    else:        
        for k,v in dic.items():
            dic[k].update({item:new_dic[k]})
   .....:             

In [124]: capitals_dict = {'USA': 'Washington', 'Russia': 'Moscow', 'Japan': 'Tokyo'}

In [125]: add_property("Capital", capitals_dict)

In [126]: add_property("demonym",capitals_dict,demonym_dict)

In [128]: capitals_dict
Out[128]: 
{'Japan': {'Capital': 'Tokyo', 'demonym': 'Japanese'},
 'Russia': {'Capital': 'Moscow', 'demonym': 'Russian'},
 'USA': {'Capital': 'Washington', 'demonym': 'American'}}
于 2013-04-26T19:20:46.380 回答