我有两本词典:
fruit1 = {'apple': 3, 'banana': 1, 'cherry': 1}
fruit2 = {'apple': 42, 'peach': 1}
Run Code Online (Sandbox Code Playgroud)
我想要的最终结果是:
inv3 = {'apple': 45, 'banana': 1, 'cherry': 1, 'peach': 1}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试过这个示例代码,因为这个输出看起来几乎与我想要的类似,只是它没有按照我想要的方式打印,而是接近:
d1 = {'apple': 3, 'orange': 1,}
d2 = {'apple': 42, 'orange': 1}
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = tuple(d[k] for d in ds)
print(ds)
Run Code Online (Sandbox Code Playgroud)
输出将是这样的:
[{'apple': 3, 'orange': 1}, {'apple': 42, 'orange': 1}]
Run Code Online (Sandbox Code Playgroud)
当我尝试使用示例代码输入我的两个词典时:
fruit1 = {'apple': 3, 'banana': 1, 'cherry': 1}
fruit2 = {'apple': 42, …
Run Code Online (Sandbox Code Playgroud) 假设我有一个词典:
firstdict = {"somelist":[]}
Run Code Online (Sandbox Code Playgroud)
我有另一个词:
seconddict = {"attribute1": "value1", "attribute2": "value2"}
Run Code Online (Sandbox Code Playgroud)
附上字典后
firstdict["somelist"].append(seconddict)
Run Code Online (Sandbox Code Playgroud)
我想打印"attribute1"值.虽然以下声明不起作用:
print firstdict["somelist"][0].attribute1
Run Code Online (Sandbox Code Playgroud)
如何打印/访问attribute1的值?
我有一个函数,它将 id、name、age、country 作为输入,并将其放入字典中的字典中,如下所示:{0:{Name: "Name1", Age: 21, Country: "Country1}}
。我打算把它放在一个数组中。
我希望我的字典数组看起来像这样:
[
{
0: {
'Name': 'Name1',
'Age': 21,
'Country': 'Country1'
},
1: {
'Name': 'Name2',
'Age': 22,
'Country': 'Country2'
},
3: {
'Name': 'Name3',
'Age': 23,
'Country': 'Country3'
}
}
]
Run Code Online (Sandbox Code Playgroud)
但是,我当前的数组如下所示:
[
{
0: {
'Name': 'Name1',
'Age': 21,
'Country': 'Country1'
}
},
{
1: {
'Name': 'Name2',
'Age': 22,
'Country': 'Country2'
}
},
{
3: {
'Name': 'Name3',
'Age': 23,
'Country': 'Country3'
}
}
]
Run Code Online (Sandbox Code Playgroud)
两者之间在括号 …
我有以下词典列表:
d = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25'},
{'Sport': 'NBA', 'Position': 'PG', 'Age': '28'}]
Run Code Online (Sandbox Code Playgroud)
我有另一个列表,我想通过使用for循环追加到上面:
c = [{'2015 Salary' : '25'}, {'2015 Salary': '35'},
{'2016 Salary' : '30'}, {'2016 Salary' : '40'}]
Run Code Online (Sandbox Code Playgroud)
我希望最终输出
e = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25', '2015 Salary': '25',
'2016 Salary': '30'},
{'Sport': 'NBA', 'Position': 'PG', 'Age': '28', '2015 Salary': '35',
'2016 Salary': '40'}}]
Run Code Online (Sandbox Code Playgroud)
这些位置总是和我使用for循环的原因相同.