简体   繁体   English

Python:如何根据特定键值仅打印字典中的实际值?

[英]Python: How to print only the actual value from a dictionary based on a specific key value?

I have a dictionary that is dynamically generated from the results of a Splunk search. 我有一本根据Splunk搜索结果动态生成的字典。 The content of the dictionary looks like this: 字典的内容如下所示:

SiteID     Reporting   Total
FLNGAASF1  3           9  
MSNGAASF2  14          26  
PANGAASF1  31          40 

Here is my Python code that generates the dictionary: 这是我生成字典的Python代码:

SiteIDs = defaultdict(list)
SiteIDs.clear()

Splunk search goes here Splunk搜索在这里

for result in results.ResultsReader(jobC.results(segmentation='none')):
   SiteID=result["SiteID"]
   Reporting=result["Reporting"]
   Total=result["Total"]
   SiteIDs[SiteID].append(('Reporting',Reporting))
   SiteIDs[SiteID].append(('Total',Total))

Now what I need to do is get the Reporting and Total numbers for specific SiteIDs. 现在,我需要获取特定SiteID的报告和总数。 For Example, suppose I want the Reporting and Total numbers for MSNGAASF2, so that I can print them in an HTML table as: 例如,假设我想要MSNGAASF2的报告号和总数,以便可以将它们打印在HTML表格中,如下所示:

14 / 26 14/26

or like this 或像这样

SiteID     Clients
FLNGAASF1  0/9  
MSNGAASF2  14/26  
PANGAASF1  0/40 

So I break out my dictionary entry like this: 所以我按如下方式分解字典条目:

Client=(SiteIDs['MSNGAASF2'])

Doing this: 这样做:

print Client,"<br />"

results in this: 结果:

[('Reporting', '14'), ('Total', '26')] [('Reporting','14'),('Total','26')]

If I try the replace function I get an error that replace is not a suported attribute in the list object. 如果尝试使用replace函数,则会收到一个错误,指出replace不是list对象中的支持属性。 No matter what I try I get an error stating that the attribute is not supported. 无论我尝试什么,都会收到一条错误消息,指出不支持该属性。

I've tried things like this but have had absolutely no luck. 我已经尝试过类似的事情,但是绝对没有运气。

print Client.get('MSNGAASF2ULLSA',0)," / ",Client.get('MSNGAASF2ULLSA',1)

and get this: 并得到这个:

print Client.get('MSNGAASF2',0)," / ",Client.get('MSNGAASF2',1) AttributeError: 'list' object has no attribute 'get' 打印Client.get('MSNGAASF2',0),“ /”,Client.get('MSNGAASF2',1)AttributeError:'list'对象没有属性'get'

All I want to do is print the values, and only the values, for the selected SiteID. 我要做的就是仅打印所选SiteID的值。 This can't be that hard but as a noob python developer I just can't seem to figure it out. 这不是那么难,但是作为一个noob python开发人员,我似乎无法弄清楚。

I need to do this because I have a second Splunk search that lists all SiteIDs and I need specific counts for each. 我需要这样做,因为我还有第二个Splunk搜索,其中列出了所有SiteID,并且我需要每个站点的特定计数。 Looping though the first Splunk search results takes forever. 尽管第一个Splunk搜索结果循环播放是永远的过程。 I'm hoping that using a dictionary will be significantly faster. 我希望使用字典会更快。

You are appending two separate tuples; 您要追加两个独立的元组; replace those two tuples with a new dictionary: 用新字典替换这两个元组:

for result in results.ResultsReader(jobC.results(segmentation='none')):
    site_id = result["SiteID"]
    reporting = result["Reporting"]
    total = result["Total"]
    SiteIDs[site_id].append({'Reporting': reporting, 'Total': total})

You could even just append the whole result dictionary rather than extract two keys. 您甚至可以只附加整个result字典,而不必提取两个键。

You can then reference those keys in your code; 然后,您可以在代码中引用这些键。 each value in SiteIDs is a list, so you'd loop over the list to get at each individual dictionary: SiteIDs中的每个值都是一个列表,因此您可以遍历该列表以获取每个单独的字典:

results = SiteIDs['MSNGAASF2']
for result in results:
    print '<td> {Reporting} </td><td> {Total} </td>'.format(**result)

I used a str.format() template here; 我在这里使用了str.format()模板 that allows you to use the keys in result in the template to pull out specific values into a string. 允许您使用模板中的result中的键将特定值提取到字符串中。

Now, if your SiteID values in the Splunk result set are always going to be unique, then using a defaultdict(list) is overkill; 现在,如果您在Splunk结果集中的SiteID值始终是唯一的,那么使用defaultdict(list)会过大。 you could just use a regular dictionary and just store the result dictionary per SiteID in there: 您可以只使用常规字典,并仅在其中存储每个SiteID的结果字典:

for result in results.ResultsReader(jobC.results(segmentation='none')):
    SiteIDs[result["SiteID"]] = result

then forgo the loop per id: 然后放弃每个ID的循环:

result = SiteIDs['MSNGAASF2']
print '<td> {Reporting} </td><td> {Total} </td>'.format(**result)

the default dictionary makes a dictionary of lists. 默认字典构成列表字典。 if you want a true dictionary you should structure it like so: 如果您想要一本真正的字典,则应该像这样构造它:

mydict = {'FLNGAASF1': {'Reporting': 3, 'Total': 9}}

you could also go: 您也可以去:

mydict['FLNGAASF1'] = {'Reporting': 3, 'Total': 9}

then to retrieve the data: 然后检索数据:

print(mydict['FLNGAASF1'])
>>> {'Reporting': 3, 'Total': 9}

full example (assuming your splunk search results is iterable): 完整的示例(假设您不满意的搜索结果是可迭代的):

mydict = {}
for row in splunk:
    mydict[row['SiteID']] = {'Reporting': row['Reporting'], 'Total': row['Total']

then just print your print your values: 然后只需打印您的值即可:

for k, v in mydict.items():  
    print("Client: %s: %d/%d" % (k, v['Reporting'], v['Total']))

>>>Client: FLNGAASF1: 3/9
>>>Client: MSNGAASF2: 14/26

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM