这是我的例子:
dictlist = [{'first': 'James', 'last': 'Joule'},
{'first': 'James','last': 'Watt'},
{'first': 'Christian','last': 'Doppler'}]
我想知道姓氏。如果这是在模型中,代码将是:
getdata = Name.objects.filter(name="Christian")
getLastName = getdata.last
我会得到"Doppler"
。
答案 0 :(得分:4)
这是一个非常简单的列表理解解决方案:
>>> dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
>>> [x['last'] for x in dictlist if x['first'] == 'Christian']
['Doppler']
答案 1 :(得分:3)
首先,我们可以有一个仅使用内置 python filter method 的简单脚本,这可能已经足够了:
fl = list(filter(lambda x: x['first'] == 'Christian', dictlist))
# you can't use `.property` because this is a dictionary, not a object
fl[0]['last']
# returns Doppler
我意识到你的例子是一个 Django 代码,所以如果你想让它更动态,以便你能够通过字典中的任何键进行过滤:
def dict_filter(dictlist: list, key: str, value: str) -> list:
return list(filter(lambda x: x.get(key) == value, dictlist))
dict_filter(dictlist, 'first', 'Christian')
# similar to django's filter method returns a queryset, this returns a list:
# [{'first': 'Christian', 'last': 'Doppler'}]
dict_filter(dictlist, 'last', 'Doppler')
# returns [{'first': 'Christian', 'last': 'Doppler'}]
dict_filter(dictlist, 'last', 'notfound')
# returns []
以及使用 python filter method 创建与 Django 的 QuerySet.get
方法类似的函数的示例:
def dict_get(dictlist: list, key: str, value: str) -> list:
ret = list(filter(lambda x: x.get(key) == value, dictlist))
if len(ret) == 0:
raise Exception('Not Found')
if len(ret) > 1:
raise Exception(f'Found more than 1 object with {key}={value}')
return ret[0]
dict_get(dictlist, 'first', 'Christian')
# returns {'first': 'Christian', 'last': 'Doppler'}
dict_get(dictlist, 'first', 'Christians')
# raises Exception: Not Found
dict_get(dictlist, 'first', 'James')
# raises Exception: Found more than 1 object with first=James
希望对你有帮助!
答案 2 :(得分:1)
这样的事情应该有效
last_name = ''
for d in dictList:
if d['first'] == 'Christian':
last_name = d['last']
break
答案 3 :(得分:1)
var express = require('express');
var router = express.Router();
var request = require('request');
var qs = require('querystring');
var configAuth = require('../config/auth');
var authorization_url_site = configAuth.iHealthAuth.authorizationSite;
var authorization_url_params = {
response_type : 'code',
client_id: configAuth.iHealthAuth.clientID,
redirect_uri: configAuth.iHealthAuth.callbackURL,
APIName : configAuth.iHealthAuth.APIName
};
var authorization_uri = authorization_url_site + '?' + qs.stringify(authorization_url_params);
var token_url_site = configAuth.iHealthAuth.tokenSite;
var token_url_params = {
grant_type : 'authorization_code',
client_id: configAuth.iHealthAuth.clientID,
client_secret: configAuth.iHealthAuth.clientSecret,
redirect_uri: configAuth.iHealthAuth.callbackURL,
code: req.query.code
};
var token_uri = token_url_site + '?' + qs.stringify(token_url_params);
// Initial page redirecting to the login page
router.route('/auth')
.get(function (req, res) {
res.redirect(authorization_uri);
});
// Callback service parsing the authorization token and asking for the access token
router.route('/')
.get(function(req, res) {
request(token_uri, function(err, response, body) {
if(err) {
throw err;
} else {
var data = JSON.parse(body);
// save token to database or file
saveToken(data);
}
});
});
});
module.exports = router;
结果 var owner = "...";
var repository = "...";
var gitHubClient = new GitHubClient(
new ProductHeaderValue("MyApp"),
new InMemoryCredentialStore(new Credentials("GitHubToken")));
var pullRequest = await gitHubClient.PullRequest.Get(owner, repository, pullRequestNumber);
Console.WriteLine("Summarising Pull Request #{0} - {1}", pullRequest.Number, pullRequest.Title);
var commits = new List<GitHubCommit>();
var moreToGet = true;
var headSha = pullRequest.Head.Sha;
while (moreToGet)
{
var comparison =
await
gitHubClient.Repository.Commits.Compare(
owner,
repository,
pullRequest.Base.Sha,
headSha);
// Because we're working backwards from the head towards the base, but the oldest commits are at the start of the list
commits.InsertRange(0, comparison.Commits);
moreToGet = comparison.Commits.Count == 250;
if (moreToGet)
{
headSha = commits.First().Sha;
}
}
仅包含:
dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
the_jameses = [d for d in dictlist if d['first'] == 'James']
答案 4 :(得分:1)
我有时喜欢使用next
:
next((d['last'] for d in dictlist if d['first'] == 'Christian'), None)
# 'Doppler'
第一个参数是一个迭代器,第二个(可选)参数是在找不到匹配项的情况下返回的默认值。
注意:这只会返回第一个匹配结果。因此,如果您希望有多个与“查询”匹配的记录,那就不好了。
答案 5 :(得分:-3)
a