简体   繁体   English

需要帮助遍历字典-Python

[英]Need help iterating through a dictionary - Python

I'm a beginner in Python. 我是Python的初学者。 I have a simple dictionary called G8_Leaders.txt - as follows: {Cameron:UK, Merkel:Germany, Obama:USA, Putin:Russia} and I'm trying to iterate through the pairs - display the contents in a column, using a basic "for" loop like so: 我有一个简单的字典,叫做G8_Leaders.txt-如下:{Cameron:UK,Merkel:Germany,Obama:USA,Putin:Russia},并且我试图遍历两对-在列中显示内容,使用基本的“ for”循环如下所示:

f0 = "G8_Leaders.txt"
f1 = open(f0)
    for i in f1:
        print(i, end=" ")
    else:
        print("Finished with Document: ", f0)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~

I'd like the results in a column, such as: 我想要列中的结果,例如:

Merkel Germany 默克尔德国

Cameron UK 卡梅伦英国

Obama USA 奥巴马美国

and so on...However, the results are only printed in one line, as they are displayed in the text file. 依此类推...但是,结果只显示在一行中,因为它们显示在文本文件中。

What is the proper way to do this? 正确的方法是什么?

First, you have to fix the representation of your dictionary in your file to be as: 首先,您必须将字典在文件中的表示形式固定为:

d = {'Cameron':'UK', 'Merkel':'Germany', 'Obama':'USA', 'Putin':'Russia'} It can be done programmatically by invoking str() on each key and value of d . d = {'Cameron':'UK', 'Merkel':'Germany', 'Obama':'USA', 'Putin':'Russia'}可以通过在每个键和值上调用str()来以编程方式完成的d Assuming that that is fixed, one solution would be: 假设这是固定的,一种解决方案是:

# Create a file for test bench: 
d = {'Cameron':'UK', 'Merkel':'Germany', 'Obama':'USA', 'Putin':'Russia'}
with open("G8_Leaders.txt", "w") as f:
    f.write(str(d) +'\n')

#Read and print from the file:
with open("G8_Leaders.txt", "r") as f:
    data = f.readlines()
for line in data:
    d = eval(line)
    for y, z in d.items():
        print(y, z)

Output: 输出:

Cameron UK
Merkel Germany
Putin Russia
Obama USA

Ok, a couple things are going on here. 好的,这里发生了几件事。 f1 is a file object, which is not what you are expecting. f1是一个文件对象,不是您所期望的。 If you want to access it as a string, you would do 如果要以字符串形式访问它,则可以

`f1_string = f1.read()`

Which reads the file into the variable f1_string as a string. f1_string文件作为字符串读取到变量f1_string中。 You could do: 您可以这样做:

for line in f1.readlines():
    # operate on one line at a time in this block

if you would prefer to read a line at a time, which will work in your case if each element is on its own line in the text file. 如果您希望一次读取一行,那么在文本文件中每个元素都位于其自己的行的情况下,这将适用于您的情况。 Since we don't know what exactly what your text file looks like, it's hard to give more specific help. 由于我们不知道您的文本文件到底是什么样子,因此很难提供更具体的帮助。 The json module people are referring to can be found here , but I'm not entirely sure that's what you want. 人们所指的json模块可以在这里找到,但是我不完全确定那是您想要的。

Assuming that your text file is just as you've described it, then try the following: 假设您的文本文件与您所描述的一样,请尝试以下操作:

    with open(f0, 'r') as f:
        for line in f:
            items = line.split(',')
            for item in items:
                leader = item.split(':')[0].replace('{','')
                country = item.split(':')[1].replace('}','')
                print(leader,country)

This should work regardless of whether or not your data has line breaks in it. 无论您的数据中是否包含换行符,此方法都应起作用。

Try this to iterate through a dictionary: 尝试通过字典进行迭代:

leaders = {'Cameron':'UK', 'Merkel':'Germany', 'Obama':'USA', 'Putin':'Russia'}
for leader in leaders:    
    print(leader, leaders[leader])
import json
print("\n".join(x+"  "+ y for x,y in json.load(open("fname.txt" ,"rb")).iteritems()))

just load it as json(at least I think its not entirely clear if you have properly formatted json in your text file ) ... (warning though dictionaries are unordered so if you need a certain order you will have to provide more clarification) 只需将其加载为json(至少我认为如果您在文本文件中正确格式化了json格式,它就不太清楚了 )...(尽管字典是无序的,所以如果您需要确定的顺序,则必须提供更多的说明)

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

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