字典中的重复值

时间:2015-11-25 00:38:30

标签: python csv dictionary

我正在尝试按以下格式读取csv文件:

number,alphabet
1,a
2,b
3,c
2,b
1,a

我创建字典的代码:

alpha = open('alpha.csv','r')
csv_alpha = csv.reader(alpha)

alpha_file = {row[0]:row[1] for row in csv_alpha}

输出:

alpha_file = { 1:'a', 2:'b', 3:'c' }

通过查看文件,1和2具有重复值。

我怎样才能将输出更改为:

alpha_file = { 1:'a', 1:'a', 2:'b', 2:'b', 3:'c' }

LNG - PYTHON

1 个答案:

答案 0 :(得分:2)

使用<ul class="" role="tablist"> <li class="listlayer6publish"><a class="btn btn-dark btnpublish btnpublishsports" href="#vtab1" role="tab" data-toggle="tab"> Sports</a></li> <li class="listlayer6publish"><a class="btn btn-dark btnpublish btnpublishsante" href="#vtab2" role="tab" data-toggle="tab"> Santé</a></li> <li class="listlayer6publish"><a class="btn btn-dark btnpublish btnpublisharts" href="#vtab3" role="tab" data-toggle="tab"> Arts</a></li> <li class="listlayer6publish"><a class="btn btn-dark btnpublish btnpublishsci" href="#vtab4" role="tab" data-toggle="tab"> Sciences et technologies</a></li> <li class="listlayer6publish"><a class="btn btn-dark btnpublish btnpublishgastro" href="#vtab4" role="tab" data-toggle="tab"> Gastronomie</a></li> <li class="listlayer6publish"><a class="btn btn-dark btnpublish btnpublishsocial" href="#vtab4" role="tab" data-toggle="tab"> Social</a></li> <li class="listlayer6publish"><a class="btn btn-dark btnpublish" href="#vtab4" role="tab" data-toggle="tab"> Autres</a></li> </ul> <div class="tab-content" id="closeme"> <div class="alert tab-pane fade" id="vtab1"> <div class="close-wrapper"> <a href="#" class="close-div">Close</a> </div> <h3 class="title">Sports</h3> <p>Trouvez des sportifs dans l'âme sur Benevolo pour vous aider dans vos tournois, compétitions.</p> </div>来保存密钥的值

list

输出将如下:

alpha = open('alpha.csv','r')
csv_alpha = csv.reader(alpha)

alpha_file = dict()
for row in csv_alpha:
    if row[0] in alpha_file:
        alpha_file[row[0]].append(row[1])
    else:
        alpha_file[row[0]] = [row[1]]

输出密钥出现次数,使用{ 1:['a','a'],2:['b','b'], 3:['c'] } 循环

for

输出如下:

d = { 1:['a','a'],2:['b','b'], 3:['c'] }
amount = []
for key, value in d.iteritems():
    amount += [key] * len(value)
print amount