我有几个词典,我想组合,如果一个键在多个词典中,值将被加在一起.例如:
d1 = {1: 10, 2: 20, 3: 30}
d2 = {1: 1, 2: 2, 3: 3}
d3 = {0: 0}
merged = {1: 11, 2: 22, 3: 33, 0: 0}
Run Code Online (Sandbox Code Playgroud)
在Python中执行此操作的最佳方法是什么?我正在看defaultdict并试图找出一些东西.我正在使用Python 2.6.
我有一个现有的字典,我想在这个字典中添加一个元组列表.
现有字典结构:
myD = {'key1': 123 , 'key2': 456}
Run Code Online (Sandbox Code Playgroud)
元组结构列表:
myL = [('fkey1',321),('fkey2',432),('fkey3',543)]
Run Code Online (Sandbox Code Playgroud)
添加元组列表后的预期字典
myD = {'key1': 123 ,'key2': 456 ,'fkey': 321 ,'fkey2': 432 ,'fkey3': 543}
Run Code Online (Sandbox Code Playgroud)
我怎么能在python中实现这个?
根据此答案,在Python 3.5或更高版本中,可以合并两个字典x
并y
解压缩它们:
z = {**x, **y}
Run Code Online (Sandbox Code Playgroud)
是否可以解压缩各种字典表?就像是
def merge(*dicts):
return {***dicts} # this fails, of course. What should I use here?
Run Code Online (Sandbox Code Playgroud)
例如,我希望
list_of_dicts = [{'a': 1, 'b': 2}, {'c': 3}, {'d': 4}]
{***list_of_dicts} == {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Run Code Online (Sandbox Code Playgroud)
请注意,此问题不是关于如何合并字典列表的问题,因为上面的链接提供了对此的答案。这里的问题是:是否有可能以及如何解压缩字典列表?
正如评论指出,这个问题是非常相似的这一个。但是,解压缩字典列表与简单地合并它们是不同的。假设有一个运算符***
旨在解开字典列表,并给出
def print_values(a, b, c, d):
print('a =', a)
print('b =', b)
print('c =', c)
print('d =', d)
list_of_dicts = [{'a': 1, 'b': …
Run Code Online (Sandbox Code Playgroud) 我有一个 pandas 数据框(示例)如下
df = pd.DataFrame({'Country':['India', 'China', 'Nepal'],
'Habitat':[[{'city1':'Ind1','city2':'Ind2'},{'town1':'IndT1','town2':'IndT2'}],
[{'city1':'Chi1','city2':'Chi2'},{'town1':'ChiT1','town2':'ChiT2'}],
[{'city1':'Nep1','city2':'Nep2'},{'town1':'NepT1','town2':'NepT2'}]],
'num':[1,2,3]
})
Run Code Online (Sandbox Code Playgroud)
df
Country Habitat num
0 India [{'city1':'Ind1','city2':'Ind2'},{'town1':'IndT1','town2':'IndT2'}] 1
1 China [{'city1':'Chi1','city2':'Chi2'},{'town1':'ChiT1','town2':'ChiT2'}] 2
2 Nepal [{'city1':'Nep1','city2':'Nep2'},{'town1':'NepT1','town2':'NepT2'}] 3
Run Code Online (Sandbox Code Playgroud)
我需要以这种格式将其展平。
result_df = pd.DataFrame({'Country':['India', 'China', 'Nepal'],
'Habitat.city1':['Ind1','Chi1','Nep1'],
'Habitat.city2':['Ind2','Chi2','Nep2'],
'Habitat.town1':['IndT1','ChiT1','NepT1'],
'Habitat.town2':['IndT2','ChiT2','NepT2'],
'num':[1,2,3]
})
Run Code Online (Sandbox Code Playgroud)
结果_df
Country Habitat.city1 Habitat.city2 Habitat.town1 Habitat.town2 num
India Ind1 Ind2 IndT1 IndT2 1
China Chi1 Chi2 ChiT1 ChiT2 2
Nepal Nep1 Nep2 NepT1 NepT2 3
Run Code Online (Sandbox Code Playgroud)
我已经尝试过pd.json_normalize(df.explode('Habitat')['Habitat])
,但它创建了我不需要的新行。
我的观察:某种形式的 groupby 和 transpose 可以正确地构建pd.json_normalize(df.explode('Habitat')['Habitat])
可以解决我的问题,但到目前为止我还没有任何运气
目前我正在使用假设 fixed_dictionaries 策略来生成一个字典,其中包含被认为对我的应用程序有效的特定键和数据类型。我需要一个策略来生成这个固定的字典以及其他删除特定键的字典。或者具有特定最小键集和可选附加键的字典,最好以产生这些可选键的各种组合的方式。
这是需要验证的 json 架构示例,带有 2 个可选字段。我想为此模式生成所有可能的有效数据。
'user_stub': {
'_id': {'type': 'string'},
'username': {'type': 'string'},
'social': {'type': 'string'},
'api_name': {'type': 'string',
'required': False},
'profile_id': {'type': 'integer',
'required': False},
}
Run Code Online (Sandbox Code Playgroud)
这是我想出的,但它是不正确的,因为它保留了键,但使用 None 作为值,而我想要删除键。
return st.fixed_dictionaries({
'_id': st.text(),
'username': st.text(),
'social': st.text(),
'api_name': st.one_of(st.none(),
st.text()),
'profile_id': st.one_of(st.none(),
st.integers()),
})
Run Code Online (Sandbox Code Playgroud)
编辑:更新复合策略 ->
似乎最好根据返回的数据类型分离额外的可选字典,否则可能会得到值不匹配的键。
@st.composite
def generate_data(draw):
base_data = st.fixed_dictionaries({
'_id': st.text(),
'username': st.text(),
'social': st.text(),
})
optional_strs = st.dictionaries(
keys=st.just('api_name'),
values=st.text()
)
optional_ints = st.dictionaries(
keys=st.just('profile_id'),
values=st.integers()
)
b = draw(base_data)
s …
Run Code Online (Sandbox Code Playgroud) 我用pySpark训练了一个随机森林。我想在结果中每个网格点都有一个csv。我的代码是:
estimator = RandomForestRegressor()
evaluator = RegressionEvaluator()
paramGrid = ParamGridBuilder().addGrid(estimator.numTrees, [2,3])\
.addGrid(estimator.maxDepth, [2,3])\
.addGrid(estimator.impurity, ['variance'])\
.addGrid(estimator.featureSubsetStrategy, ['sqrt'])\
.build()
pipeline = Pipeline(stages=[estimator])
crossval = CrossValidator(estimator=pipeline,
estimatorParamMaps=paramGrid,
evaluator=evaluator,
numFolds=3)
cvModel = crossval.fit(result)
Run Code Online (Sandbox Code Playgroud)
所以我想要一个csv:
numTrees | maxDepth | impurityMeasure
2 2 0.001
2 3 0.00023
Run Code Online (Sandbox Code Playgroud)
等等
做这个的最好方式是什么?
我有一个清单,说:
NUM = 100
my_list = list(range(NUM))
Run Code Online (Sandbox Code Playgroud)
我想生成一个dict
键等于值的东西,比如:
my_dict = {item: item for item in my_list}
Run Code Online (Sandbox Code Playgroud)
或者:
my_dict = dict(zip(my_list, my_list))
Run Code Online (Sandbox Code Playgroud)
我已经运行了一些微基准测试,看起来它们的速度相似,但我希望第二个会更快,因为循环应该在 C 中发生。
例如,以下构造:
my_dict = {key: SOMETHING for key in keys}
Run Code Online (Sandbox Code Playgroud)
翻译成更快:
my_dict = dict.fromkeys(k, SOMETHING)
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是:有没有类似的这样的构造{x: x for x in my_list}
?
我已经检查过dir(dict)
,在这个方向上似乎没有任何东西(我希望它被称为类似的东西dict.fromitems()
)。
dict.fromitems()
与此特定用例相比,类似的方法具有更广泛的应用,因为:
dict.fromitems(keys, values)
Run Code Online (Sandbox Code Playgroud)
原则上可以同时替代两者:
{k, v for k, v in zip(keys, values)}
Run Code Online (Sandbox Code Playgroud)
和:
dict(zip(keys, values))
Run Code Online (Sandbox Code Playgroud) 我正在使用glom项目.
有没有办法转换[{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}]
成{1: "foo", 2: "bar"}
?
对 python 来说相当陌生,所以这可能看起来很菜鸟。我创建了两个 .line 格式的基本地图(对我来说是新的),每个地图都使用 matplotlib 显示不同的功能。这些地图是从单独的形状文件转换而来的。现在我需要将这两个 .line 地图合并为一个。
任何想法将不胜感激。TY。
我有一本以下格式的字典:
data = {
'Bob': {
'age': 12,
'weight': 150,
'eye_color': 'blue'
},
'Jim': {
'favorite_food': 'cherries',
'sport': 'baseball',
'hobby': 'running'
},
'Tom': {
'strength': 'average',
'endurance': 'high',
'heart_rate': 'low'
}
}
Run Code Online (Sandbox Code Playgroud)
将 dict 中的所有字典连接成一个新字典的最 Pythonic 方法是什么,这样我最终会得到如下所示的结果:
new_dict = {
'age': 12,
'weight': 150,
'eye_color': 'blue',
'favorite_food': 'cherries',
'sport': 'baseball',
'hobby': 'running',
'strength': 'average',
'endurance': 'high',
'heart_rate': 'low'
}
Run Code Online (Sandbox Code Playgroud) python ×10
dictionary ×4
merge ×2
python-3.x ×2
apache-spark ×1
glom ×1
list ×1
pandas ×1
performance ×1
pyspark ×1
testing ×1
unit-testing ×1