在这里,我们将给大家分享关于如果键多次出现而不导入,如何更新python字典中的值?的知识,让您更了解python字典中的“键”不允许重复的本质,同时也会涉及到如何更有效地python–如何比较字典中
在这里,我们将给大家分享关于如果键多次出现而不导入,如何更新python字典中的值?的知识,让您更了解python字典中的“键”不允许重复的本质,同时也会涉及到如何更有效地python – 如何比较字典中的值?、python 字典中的值、Python-字典中的值求和、python字典中如何一键多值的写入?的内容。
本文目录一览:- 如果键多次出现而不导入,如何更新python字典中的值?(python字典中的“键”不允许重复)
- python – 如何比较字典中的值?
- python 字典中的值
- Python-字典中的值求和
- python字典中如何一键多值的写入?
如果键多次出现而不导入,如何更新python字典中的值?(python字典中的“键”不允许重复)
尝试使用 collections.defaultdict
:
from collections import defaultdict
yourlist = [("John",14),("Bob",5),("John",21)]
d = defaultdict(list)
for k,v in yourlist:
d[k].append(v)
print(d)
输出:
defaultdict(<class 'list'>,{'John': [14,21],'Bob': [5]})
要使其成为真正的 dict
ionary,请添加以下行:
d = dict(d)
那么:
print(d)
会给:
{'John': [14,'Bob': [5]}
编辑:
正如 OP 在评论中提到的,他不想使用任何导入。所以试试:
yourlist = [("John",21)]
d = {}
for x,y in yourlist:
if x in d:
d[x].append(y)
else:
d[x] = [y]
print(d)
输出:
{'John': [14,'Bob': [5]}
,
正如 nike
所说...就去做吧:
my_dict = {}
for item in list_of_tuples:
if item[0] not in my_dict.keys():
my_dict[item[0]] = [item[1]]
else:
my_dict[item[0]].append(item[1])
这将确保不在字典中的任何键都获得分配给它们的列表值
您需要成员资格检查,因为您将通过 .append()
添加值,这是一种 NoneType
没有的方法,因此如果您尝试直接创建键/值对,则会抛出错误
您可以通过简单的(如果不是最佳的)理解来做到这一点:
>>> data = [("John",21)]
>>> {name: [v for k,v in data if k == name] for name,_ in data}
{'John': [14,'Bob': [5]}
python – 如何比较字典中的值?
{'METTS MARK': {'salary': 365788,'to_messages': 807,'deferral_payments': 'NaN','total_payments': 1061827,'exercised_stock_options': 'NaN','bonus': 600000,'restricted_stock': 585062,'shared_receipt_with_poi': 702,'restricted_stock_deferred': 'NaN','total_stock_value': 585062,'expenses': 94299,'loan_advances': 'NaN','from_messages': 29,'other': 1740,'from_this_person_to_poi': 1,'poi': False,'director_fees': 'NaN','deferred_income': 'NaN','long_term_incentive': 'NaN','email_address': 'mark.metts@enron.com','from_poi_to_this_person': 38},'BAXTER JOHN C': {'salary': 267102,'to_messages': 'NaN','deferral_payments': 1295738,'total_payments': 5634343,'exercised_stock_options': 6680544,'bonus': 1200000,'restricted_stock': 3942714,'shared_receipt_with_poi': 'NaN','total_stock_value': 10623258,'expenses': 11200,'from_messages': 'NaN','other': 2660303,'from_this_person_to_poi': 'NaN','deferred_income': -1386055,'long_term_incentive': 1586055,'email_address': 'NaN','from_poi_to_this_person': 'NaN'},'ELLIott STEVEN': {'salary': 170941,'total_payments': 211725,'exercised_stock_options': 4890344,'bonus': 350000,'restricted_stock': 1788391,'total_stock_value': 6678735,'expenses': 78552,'other': 12961,'deferred_income': -400729,'email_address': 'steven.elliott@enron.com','from_poi_to_this_person': 'NaN'} }
这只是字典的一小部分.我将如何使用for循环遍历每个子词典的工资值,并将其与下一个词典进行比较,以找出谁拥有最高薪水?我正在尝试这样的事情:
big = 0 for i in data_dict: if data_dict[i]["salary"] > big: big = i print i
但它并没有给我正确答案.另外,我如何使用for循环来检查谁拥有最高薪水和最大奖金?任何帮助将不胜感激.谢谢.
解决方法
你可以使用关键函数使用字典上的max来更有效地计算最大值和“pythonic”,这是一个元组工资/奖金(所以相同的工资:奖金比较):
print(max(d,key=lambda x : (d[x]["salary"],d[x]["bonus"])))
这给了我
METTS MARK
python 字典中的值
要访问字典元素,您可以使用熟悉的方括号,随着关键,以获得其价值:例如:
#!/usr/bin/python
dict = {''Name'': ''Zara'', ''Age'': 7, ''Class'': ''First''};
print "dict[''Name'']: ", dict[''Name''];
print "dict[''Age'']: ", dict[''Age''];
这将输出以下结果: 打鱼游戏机大型游戏机
dict[''Name'']: Zara
dict[''Age'']: 7
Python-字典中的值求和
我有很简单的清单:
example_list = [
{'points': 400,'gold': 2480},{'points': 100,'gold': 610},'gold': 620},'gold': 620}
]
我如何求和所有 黄金 价值?我正在寻找不错的oneliner。
现在,我正在使用以下代码(但这不是最佳解决方案):
total_gold = 0
for item in example_list:
total_gold += example_list["gold"]
python字典中如何一键多值的写入?
python字典中一键多值写入的方法:
1、循环写入字典key、value、删除指定的键值对:
原文本‘jp_url.txt’每行元素以逗号分隔:
立即学习“Python免费学习笔记(深入)”;
host_key,product_id,product_name,cont_start,cont_end ah2.zhangyue.com,100002,掌阅,bookId=,&startChapterId ih2.ireader.com,100002,掌阅,bid=,& www.ireader.com,100002,掌阅,&bid=,&cid m.zhangyue.com,100002,掌阅,readbook/,/ c13.shuqireader.com,100003,书旗,bookId=,&chapterId t.shuqi.com,100003,书旗,bid/,/cid 想要得到: {‘100002’:‘product_name’.......}
代码如下:
def makeDict(): fileRead=open('jp_url.txt','rb') lines=fileRead.readlines() read_dict={}#定义字典 for line in lines: line_list=line.split(',')#每行按逗号分隔成列表 id=line_list[1]#取到id name=line_list[2]#取到name read_dict[id]=name#此处关键产生键值对,其中key是id read_dict.pop('product_id')#删除key为‘product_id’的键值对 return read_dict read_dict=makeDict()
2、循环写入一键对多值:
其中格式{key:[value1,value2,...]}
文本txt格式如下:
guaguashipinliaotianshi|.guagua.cn,
guaguashipinliaotianshi|iguagua.net,
guaguashipinliaotianshi|.17guagua.com,
jiuxiumeinvzhibo|.69xiu.com,
nbazhibo|.estream.cn,
youbo|yb.sxsapp.com,
其中第一列的名字有重复想要一个名字对应多个结果,代码如下:
def makehostDict(): host_dict={} f_allhost=open('xml_host.txt','rb') lines=f_allhost.readlines() for line in lines: line_list=line.split('|') name=line_list[0] host=line_list[1].strip('\n') if host is not '': if host_dict.has_key(name): host_dict.get(name).append(host)#此处为关键向字典里已经有的key(name)值后继续添加value(host) else: host_dict.setdefault(name,[]).append(host)#创建{name,[host]}value为列表的格式的字典。 return host_dict host_dict=makehostDict() print host_dict
推荐教程:《python视频教程》
以上就是
今天关于如果键多次出现而不导入,如何更新python字典中的值?和python字典中的“键”不允许重复的讲解已经结束,谢谢您的阅读,如果想了解更多关于python – 如何比较字典中的值?、python 字典中的值、Python-字典中的值求和、python字典中如何一键多值的写入?的相关知识,请在本站搜索。
本文标签: