Python更新字典键与字典值

时间:2017-12-27 06:44:20

标签: python dictionary

如果你有这样的词典:

{"key1":{"month":"2017-01","randomNumber":32}}

有没有办法使用以下内容添加/更新key1

{"month":"2017-02","randomNumber":12}

这样结果将是一个字典字典,其输出如下:

{"key1":{"month":"2017-01","randomNumber":32},{"month":"2017-02","randomNumber":12}}

我尝试的所有内容都会导致嵌套字典,因为每次都会覆盖该值,而不是将新字典附加到上一个值,因此输出为:

{"key1":{"month":"2017-02","randomNumber":12}}

任何帮助都将不胜感激。

代码示例:

theKeys = ['key1','key2','key3']
sDate = "2017-01-01"
eDate = "2017-12-31"
data = defaultdict(dict)
for aKey in theKeys:
    for dt in rrule.rrule(rrule.MONTHLY, dtstart=sDate, until=eDate):
        year = dt.strftime("%Y")
        month = dt.strftime("%m")
        daysInMonth = str(monthrange(int(year),int(dt.strftime("%m")))[1])
        firstDateMonth = year + "-" + month + "-" "1"
        lastDateMonth = year + "-" + month + "-" + daysInMonth  

        dataResults = {}
        dataResults["month"] = year + "-" + month
        dataResults["randomNumber"] = randint(1, 100)

        data[aKey].update(dataResults)

2 个答案:

答案 0 :(得分:0)

您已经创建了字典字典。

{"key1":{"month":"2017-01","randomNumber":32}}

上面是一个dict,密钥为key1,其值也是dict

您需要创建一个list dict&将新dict附加到该列表。以下是示例。

>>> a = dict(q=1,w=[dict(e=3)])
>>> a
{'q': 1, 'w': [{'e': 3}]}
>>> a.get('w')
[{'e': 3}]
>>> a.get('w').append(dict(r=4))
>>> a
{'q': 1, 'w': [{'e': 3}, {'r': 4}]}
>>> a.get('w').append(dict(e=4))
>>> a
{'q': 1, 'w': [{'e': 3}, {'r': 4}, {'e': 4}]}
>>> 

答案 1 :(得分:0)

将键的值设置为列表,并将新元素附加到列表

K = {"key1":[{"month":"2017-01","randomNumber":32},{"month":"2017-02","randomNumber":12}]}
K['key1'].append({"month":"2017-03","randomNumber":42})

结果:

{'key1': [{'randomNumber': 32, 'month': '2017-01'}, {'randomNumber': 12, 'month': '2017-02'}, {'randomNumber': 42, 'month': '2017-03'}]}