[英]Random sampling from dictionary list values based on an integar value from another dictionary, with matching keys
[英]How to add values from one dictionary to another based on matching keys?
我有两个具有匹配键和不同值的字典。 我想将a的值添加到b。
某些键在字典a中而不在b中。 我想跳过这些。
a = {1:"a", 2:"b", 3:"c", 4:"d"}
b = {1:"e", 2:"f", 3:"g"}
for k, v in a.items():
if k in b.keys():
list(b).append(v)
else: print 'Could not locate key', k
我希望输出是b = {1:[“ e”,“ a”],2:[“ b”,“ f”],3:3:[“ g”,“ c”]}
而是不附加值。 我也尝试在v周围使用方括号,该括号将返回
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
我想这就是您想要的...我使用字符串作为原始值,但仍可用于列表。
>>> a = {"1":"a", "2":"b", "3": "c", "4":"d"}
>>> b = {"1":"e", "2":"f", "3":"g"}
>>> for k, v in a.items():
... if k in b:
... b[k] = [a[k], b[k]]
...
>>> b
{'1': ['a', 'e'], '2': ['b', 'f'], '3': ['c', 'g']}
这是您想要的吗?
a = {1:"a", 2:"b", 3:"c", 4:"d"}
b = {1:"e", 2:"f", 3:"g"}
c={}
keys = set(list(a.keys())+list(b.keys()))
for key in keys:
items = []
items += [a[key]] if key in a else []
items += [b[key]] if key in b else []
c[key]=items
a = {1:"a", 2:"b", 3:"c", 4:"d"}
b = {1:"e", 2:"f", 3:"g"}
for k, v in a.items():
if k in b.keys():
b[k] = [v,b[k]]
else: print('Could not locate key', k)
print(b)
output :
Could not locate key 4
{1: ['a', 'e'], 2: ['b', 'f'], 3: ['c', 'g']}
使用b [k] = [v,b [k]]代替list(b).append(v)
list(b).append(v)表示您正在创建字典b的键列表,然后将v附加到该列表
b [k] = [v,b [k]]表示为键k创建字典a和b的值列表,并在键k处分配给字典b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.