如何在python的嵌套字典中获取文件的内容?

2024-06-25 05:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试读取一个txt文件,并将内容放入嵌套字典中。文件内容如下

Name: John Doe
Email: john.doe@exabeam.com

Name: Martina jackson
Email: Martina.jackson@exabeam.com

Name: Steve Bob
Email: steve.bob@exabeam.com

Name: John Doe
Email: john.doe@exabeam.com

Name: Steve Bob
Email: steve.bob@exabeam.com

Name: John Doe
Email: john.doe@exabeam.com

我的目的是对文件内容进行排序,以便“name”应该是键,对于每个“name”,电子邮件被提及的次数应该作为一个值出现在嵌套dict中。以下是示例输出:

{ "John Doe": {"John.doe@exabeam.com": 3}, "Steve Bob": {"steve.bob@exabeam.com": 2}, "Martina Jackson":{"martina.jackson": 1}} 

所以,我尝试了如下的方法。但它不起作用

with open('contacts', 'r') as file:
    for read_file in file:
        new_dict = sorted(read_file.items(), key = lambda x: x[1]['point'],reverse=True)
        print(new_dict)

当我执行上述程序时,我得到以下错误:

 new_dict = sorted(read_file.items(), key = lambda x: x[1]['point'],reverse=True)
AttributeError: 'tuple' object has no attribute 'items'

有什么想法吗

谢谢,


Tags: 文件namecom内容emailjohndictfile
3条回答

像这样的

contacts = {}
with open('contacts.txt', 'r') as f:
  name = None

  for line in f:
    parts = line.rstrip().split(': ')

    if parts[0] == 'Name':
      name = parts[1]

      if name not in contacts:
        contacts[name] = {} # Initialize empty dict for new name

    elif parts[0] == 'Email':
      email = parts[1]

      if email not in contacts[name]:
        contacts[name][email] = 0 # Initialize count for new email

      contacts[name][email] += 1

print(contacts) # Outputs: {'John Doe': {'john.doe@exabeam.com': 3}, 'Martina jackson': {'Martina.jackson@exabeam.com': 1}, 'Steve Bob': {'steve.bob@exabeam.com': 2}} 


又是一个例子

with open('contacts', 'r') as file:
    for read_file in file.read().split("\n\n"): #data chunks apart
        data = read_file.split("\n") #split email/name
        name = data[0].split(" ")[1] #split at space and grab second
        email = data[1].split(" ")[1] #^
        if name not in d:
            d[name] = {email:1}
        else:
            d[name][email] += 1

这个怎么样

result = {}

with open(filename, "r") as f:
    lines = f.readlines()
    
    for name_line, address_line in zip(lines[::3], lines[1::3]):
        name = name_line.replace(": ", ":").split(":")[1].strip()
        address = address_line.replace(": ", ":").split(":")[1].strip()

        if not name in result:
            result[name] = {address: 1}
        else:
            result[name][address] += 1

相关问题 更多 >