有没有一种简单的方法可以在Python中删除字典属性时可能不存在该属性?
如果使用该del语句,则结果是KeyError:
a = {}
del a['foo']
>>>KeyError: 'foo'
Run Code Online (Sandbox Code Playgroud)
它有点罗嗦使用if语句,你必须输入'foo'和a两次:
a = {}
if 'foo' in a:
del a['foo']
Run Code Online (Sandbox Code Playgroud)
如果属性不存在,则寻找类似于dict.get()默认值的None值:
a = {}
a.get('foo') # Returns None, does not raise error
Run Code Online (Sandbox Code Playgroud) 我有一本这样的字典:
inventory = {'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'],
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}
Run Code Online (Sandbox Code Playgroud)
怎样才能把匕首从里面取出来呢?
我试过这个:
inventory["backpack"][1].remove()
Run Code Online (Sandbox Code Playgroud)
或者
del inventory["backpack"][1]
Run Code Online (Sandbox Code Playgroud)
但它犯了这个错误:
Traceback (most recent call last):
File "python", line 15, in <module>
TypeError: 'NoneType' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud) 我的会话变量是'cart':
cart = {'8': ['a'], ['b'], '9': ['c'], ['d']}
Run Code Online (Sandbox Code Playgroud)
如果我想删除我的所有购物车变量,我只需在Python中执行此操作:
del request.session['cart']
Run Code Online (Sandbox Code Playgroud)
但我只是想删除键'8',所以我尝试这个但它不起作用:
del request.session['cart']['8']
Run Code Online (Sandbox Code Playgroud)
但是,如果我打印request.session ['cart'] ['8']并获得a,b
我有2个词典,A和B. A有700000个键值对,B有560000个键值对.来自B的所有键值对都存在于A中,但A中的某些键是具有不同值的重复项,而某些键具有重复值但是唯一键.我想从A中减去B,所以我可以得到剩余的140000个键值对.当我根据键标识减去键值对时,由于重复键,我删除了150000个键值对.我想根据每个键值对的BOTH键和值的标识减去键值对,所以我得到140000.任何建议都是受欢迎的.
这是一个例子:
A = {'10':1, '11':1, '12':1, '10':2, '11':2, '11':3}
B = {'11':1, '11':2}
Run Code Online (Sandbox Code Playgroud)
我想得到:AB = {'10':1,'12':1,'10':2,'11':3}
我不想得到:
a)基于密钥时:
{'10':1, '12':1, '10':2}
Run Code Online (Sandbox Code Playgroud)
要么
b)基于价值观:
{'11':3}
Run Code Online (Sandbox Code Playgroud) 我在通过 FastAPI 插入 MongoDB 时遇到一些问题。
下面的代码按预期工作。请注意该response变量尚未在 中使用response_to_mongo()。
这model是一个 sklearn ElasticNet 模型。
app = FastAPI()
def response_to_mongo(r: dict):
client = pymongo.MongoClient("mongodb://mongo:27017")
db = client["models"]
model_collection = db["example-model"]
model_collection.insert_one(r)
@app.post("/predict")
async def predict_model(features: List[float]):
prediction = model.predict(
pd.DataFrame(
[features],
columns=model.feature_names_in_,
)
)
response = {"predictions": prediction.tolist()}
response_to_mongo(
{"predictions": prediction.tolist()},
)
return response
Run Code Online (Sandbox Code Playgroud)
但是,当我predict_model()这样写并将response变量传递给response_to_mongo():
@app.post("/predict")
async def predict_model(features: List[float]):
prediction = model.predict(
pd.DataFrame(
[features],
columns=model.feature_names_in_,
)
)
response = {"predictions": prediction.tolist()} …Run Code Online (Sandbox Code Playgroud) 我正在尝试从字典中创建一个pandas数据帧.字典设置为
nvalues = {"y1": [1, 2, 3, 4], "y2": [5, 6, 7, 8], "y3": [a, b, c, d]}
Run Code Online (Sandbox Code Playgroud)
我希望数据帧只包括"y1"和" y2".到目前为止,我可以使用
df = pd.DataFrame.from_dict(nvalues)
df.drop("y3", axis=1, inplace=True)
Run Code Online (Sandbox Code Playgroud)
我想知道是否有可能在没有的情况下实现这一目标 df.drop()
我有以下示例数据作为 python 中的列表对象。
[{'itemdef': 10541,
'description': 'Dota 2 Just For Fun tournament. ',
'tournament_url': 'https://binarybeast.com/xDOTA21404228/',
'leagueid': 1212,
'name': 'Dota 2 Just For Fun'},
{'itemdef': 10742,
'description': 'The global Dota 2 league for everyone.',
'tournament_url': 'http://www.joindota.com/en/leagues/',
'leagueid': 1640,
'name': 'joinDOTA League Season 3'}]
Run Code Online (Sandbox Code Playgroud)
我如何从这个列表中删除描述,tour_url;或者我怎么能只保留名称和 Leagueid 键。我尝试了各种解决方案,但似乎都不起作用。
第二个问题:如何过滤此列表?如在 mysql 中:
select *
from table
where leagueid = 1212
Run Code Online (Sandbox Code Playgroud)
请把我当成一个 Python 新手,因为我真的是。
我在Windows 7中使用Python 2.7.
我有一个字典,并希望从另一个字典中删除与(键,值)对相对应的值.
例如,我有一本字典t_dict.我想删除字典中的相应(键,值)对,values_to_remove以便我最终得到字典final_dict
t_dict = {
'a': ['zoo', 'foo', 'bar'],
'c': ['zoo', 'foo', 'yum'],
'b': ['tee', 'dol', 'bar']
}
values_to_remove = {
'a': ['zoo'],
'b': ['dol', 'bar']
}
# remove values here
print final_dict
{
'a': ['foo', 'bar'],
'c': ['zoo', 'foo', 'yum'],
'b': ['tee']
}
Run Code Online (Sandbox Code Playgroud)
我已经查看了关于SO和python词典文档的类似页面,但找不到任何解决这个特定问题的东西:
https://docs.python.org/2/library/stdtypes.html#dict
编辑
t_dict每个键中不能有重复的值.例如,永远不会有
t_dict['a'] = ['zoo','zoo','foo','bar']
我甚至不确定该怎么称呼它,所以很难搜索.我有,例如,
people = [
{"age": 22, "first": "John", "last": "Smith"},
{"age": 22, "first": "Jane", "last": "Doe"},
{"age": 41, "first": "Brian", "last": "Johnson"},
]
Run Code Online (Sandbox Code Playgroud)
我想要类似的东西
people_by_age = {
22: [
{"first": "John", "last": "Smith"},
{"first": "Jane", "last": "Doe"},
],
41: [
{"first": "Brian", "last": "Johnson"}
]
}
Run Code Online (Sandbox Code Playgroud)
在Python 2中最干净的方法是什么?
python ×8
dictionary ×6
list ×3
python-2.7 ×3
django ×1
fastapi ×1
mongodb ×1
pandas ×1
pymongo ×1
python-3.x ×1
subtraction ×1