Python 从列表中获取键和值

Python 从列表中获取键和值,python,list,dictionary,matplotlib,Python,List,Dictionary,Matplotlib,我在制作字典和从名称和值列表中获取键和值时遇到问题 列表如下所示: ['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845'] 我的问题是如

我在制作字典和从名称和值列表中获取键和值时遇到问题

列表如下所示:

['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845']
我的问题是如何将名称作为键,将数字作为值

如果键已经在字典中,它将把这些值相加

然后我如何用它做一个饼图

我只是在学习python,我想不出这个

def strany():
slovnik={}
zoznam=[]
x=open('Strany.txt','r')
for i in x.readlines():
    i=i.strip()
    casty=i.split(' ')
    for x in casty:
        zoznam.append(x)
我不知道如何继续下去


谢谢您的建议。

只需重复浏览列表,按两步走,然后取出每个键/值。像这样

l = ['1','a','2','b','3','c']
for i in range(0, len(l), 2):
    print('key=' + l[i] + 'value=' + l[i+1])
将打印功能替换为适合您的问题的功能

import matplotlib.pyplot as plt

summed = {}
x = ['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845']
it = iter(x)
for k,v in zip(it,it):
    summed[k] = summed.get(k,0) + float(v)

plt.pie(summed.values(), labels=summed.keys())
plt.show()
若要处理文件部分,假设您希望在文件中的所有行中使用一个饼图:

import matplotlib.pyplot as plt

with open('Strany.txt') as f:
    it = (y for z in f for y in z.strip().split())

summed = {}
for k,v in zip(it,it):
    summed[k] = summed.get(k,0) + float(v)

plt.pie(summed.values(), labels=summed.keys())
plt.show()

统计局正在为选举做准备吗?木荷荷荷

result = {}
a=['smer', '8', 'kdh', '7', 'smer', '6']
while a:
    party = a.pop(0)
    number = int(a.pop(0))
    if (party in result.keys()):
        result[party]+=number
    else:
        result[party]=number
您可以对重复键的值进行求和,调用列表中的
ite
r,并在压缩后将每个配对解压缩到一个循环中:

l = ['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845']

from collections import defaultdict

d = defaultdict(int)
it = iter(l)
for k,v in zip(it,it):
    d[k] += int(v)

print(d) 
defaultdict(<class 'int'>, {'sns': 78, 'ol': 5939, 'du': 8266, 'smer': 2586, 'most-hid': 1691, 'kdh': 8400})
您可以使用常规dict和
dict.setdefault
实现相同的功能:

with open("infile") as f:
    d = {}
    for k,v in csv.reader(f,delimiter=" "):
        d.setdefault(k , 0)
        d[k] += int(v)

您可以从列表中创建一个迭代器,并使用它的
next
方法

lt_iter= iter(lst)
dic={}
while True:
    try:
        key=lt_iter.next()
        value= lt_iter.next()
        if key in dic:
            dic[key]+=value
        else:
            dic[key]=value
    except StopIteration:
        break

print dic

加载到字典很容易,但您需要一个类似于生成饼图的绘图库

#load the value in the list
k = ['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845']

#create a dictionary to hold the values
d = {}

for i in range(0,len(k),2):#iterate the length of the list, i will be every other index
    key = k[i]
    val = float(k[i+1])
    if d.has_key(key): #if the key exists perform summation
        d[key] += val
    else: #if the key does not exist create it
        d[key] = val

# a plotting library like matplot lib is required for the pie chart
import matplotlib.pyplot as plt
labels = d.keys()
values = d.values()

plt.pie(values,              # data
        labels=labels,      # slice labels
        autopct='%1.1f%%',  # print the values inside the wedges
        )

plt.show()

你试过什么?什么东西不起作用?你犯了什么错误?你的代码是什么样子的?首先不要构建列表。直接从文件构建dict要容易得多。当您建立列表时,您将丢失文件提供给您的自然分组对。@user2357112,这对重复无效keys@PadraicCunningham:对,我刚看到那部分。不过,直接构建dict更容易;这已经不是一行了。先看问题。不幸的是,是的,但这是一个额外的家庭作业,所以我试着去做,但现在我成功了hurry@Padraic坎宁安,你是100%对的。你的答案是真实的python我的答案是“python for dummies”(无意冒犯)。我不想冒犯,但这不应该是赢家。下面有更好的答案
#load the value in the list
k = ['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845']

#create a dictionary to hold the values
d = {}

for i in range(0,len(k),2):#iterate the length of the list, i will be every other index
    key = k[i]
    val = float(k[i+1])
    if d.has_key(key): #if the key exists perform summation
        d[key] += val
    else: #if the key does not exist create it
        d[key] = val

# a plotting library like matplot lib is required for the pie chart
import matplotlib.pyplot as plt
labels = d.keys()
values = d.values()

plt.pie(values,              # data
        labels=labels,      # slice labels
        autopct='%1.1f%%',  # print the values inside the wedges
        )

plt.show()