How Can I Take Multiple Lines of a Text File as the Values (In a Tuple) for a Key in a Dictionary?

How Can I Take Multiple Lines of a Text File as the Values (In a Tuple) for a Key in a Dictionary?

store values in dictionary python
dictionary comprehension python
sort dictionary by value python
add the key value pair color red to the car dictionary
how to get dictionary values in python
python dictionary keys
python dictionary of dictionaries
python dictionary get key from value

I'm trying to read a text file and then create a dictionary using the data in that file. An example of the text would be:

100
Mulan
300, 500
200, 400

200
Ariel
100, 500
500

300
Jasmine
500
500, 100

400
Elsa
100, 500


500
Belle
200, 300
100, 200, 300, 400

I need to take the first line as the key for my dictionary, and the second, third, and fourth lines as the value for that key.

So far, my code looks like this:

`file = open(file_name,"r")
d = {}
for line in file.readlines():
    line = line.split()
    if not line:
        continue
    d[line[0]] = line[1:]
return d`

But this returns something weird:

{'100': [], 'Mulan': [], '300,': ['500'], '200,': ['300'], '200': [], 'Ariel': [], '100,': ['200,', '300,', '400'], '500': [], '300': [], 'Jasmine': [], '500,': ['100'], '400': [], 'Elsa': [], 'Belle': []}

Clearly, the function is taking the first value of each line as a key, which is not what I want. I need the output to look like this:

{100: ('Mulan', [300, 500], [200, 400]), 
200: ('Ariel', [100, 500], [500]), 
300: ('Jasmine', [500], [500, 100]), 
400: ('Elsa', [100, 500], []), 
500: ('Belle', [200, 300], [100, 200, 300, 400])}

Can anyone help me figure out how to accomplish this, or specifically how to take multiple lines from the text file to use as a value in my dictionary?


This should be a shorter and hopefully more intuitive way to do it:

import itertools

file_name = 'sample.txt'
d = {}
expected_lines = 4

with open(file_name, 'r') as f:
    blocks = list("".join(group) for empty, group in itertools.groupby(f, key=str.isspace) if not empty)

for block in blocks:
    lines = [[int(i) for i in i.split(',')] if len(i.split(',')) > 1 
                                            else i for i in block.split('\n')][:expected_lines]
    lines = [[] if i == '' else i for i in lines]
    d[lines[0]] = tuple(lines[1:])

d
{'100': ('Mulan', [300, 500], [200, 400]),
 '200': ('Ariel', [100, 500], '500'),
 '300': ('Jasmine', '500', [500, 100]),
 '400': ('Elsa', [100, 500], []),
 '500': ('Belle', [200, 300], [100, 200, 300, 400])}

When you open the file here, we are using the with context manager and splitting the file by blocks separated by empty newlines using Python's standard module library's itertools.groupby. Then for every block, use the first item as a key in the dictionary and put every subsequent item in a tuple. It also returns integer pairs as a list and returns an empty list if it does not meet the expected number of lines as per your example.


Another interesting scenario to consider is when you have missing lines between your keys and values, where the solution above will not provide the proper output, for example:

300
Jasmine
500
500, 100

400

100, 500

For this scenario, we expect the data to be chunks of 5, including the newline. Then we can utilize a grouper function from the Python recipe here, to grab 5 rows at a time from the file. We can also use a helper function to explicitly return your data from your integer pairs accordingly.

import itertools

file_name = 'sample.txt'
d = {}
expected_lines = 5

def grouper(iterable, n, fillvalue=''):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

def check_empty(int_pairs):
    int_pairs = int_pairs.split()
    if len(int_pairs) > 1:
        return int_pairs
    else:
        return []

with open(file_name, 'r') as f:
    blocks = list(grouper(f, expected_lines, fillvalue=''))

for block in blocks:
    lines = [i.replace('\n','') for i in block if i][:expected_lines-1]
    d[int(lines[0])] = (lines[1],check_empty(lines[2]),check_empty(lines[3]))

This will work for files with missing lines where the row number indicates the data chunk or structure.

Using dictionaries to store data as key-value pairs, The dictionary stores objects as key-value pairs and can be used to represent will return a text file (in JSON format) that can be turned into a Python dictionary: a for-loop, we can take advantage of a feature referred to as tuple unpacking. as just a really convenient way to assign more than one variable in a single line. need to get values retied for second, third as well. I’m not really sure what this means. The relevance I provided should give the first part of both lines, not just a single value.


option 1

Looking at your example it seems, that there have to be two lists after the name. If the 2nd one is empty, you want to have an empty list there. So you forced already this structure of "5 lines define a dictionary entry" on your data.. You might as well use it when reading it:

from pprint import pprint

with open('data.txt', 'r') as F:
    lines = [line.replace('\n','') for line in F.readlines()]


n = len(lines)
d = 5                   # number of lines for one entry in the file

if not n%d==0:
    for i in range(d-n%d):
        lines.append('')    

result = {}
for i, line in enumerate(lines):
    if   i%5==0: key  = int(line)
    elif i%5==1: name = line.rstrip()
    elif i%5==2: 
        if line=='': num1 = []
        else: num1 = [int(x) for x in line.replace(' ','').split(',')]
    elif i%5==3:
        if line=='': num2 = []
        else: num2 = [int(x) for x in line.replace(' ','').split(',')]  
    elif i%5==4: result[key] = (name, num1, num2)

pprint(result)

Which results in exactly what you want.

{100: ('Mulan', [300, 500], [200, 400]),
 200: ('Ariel', [100, 500], [500]),
 300: ('Jasmine', [500], [500, 100]),
 400: ('Elsa', [100, 500], []),
 500: ('Belle', [200, 300], [100, 200, 300, 400])}

The "if not n%d==0:" part adds empty lines until there is a total which is a multiple of 5. This way the "belle" entry is added even tough there are only 24 lines in your data file.

option 2

If you do not really need that empty list there, you might work from here:

with open('data.txt', 'r') as F:
    lines = F.readlines()


long_line = ''.join([x.replace(' ','') for x in lines])
split     = [x.lstrip().split('\n') for x in long_line.split('\n\n')]


result    = {}
for e in split:
    result[int(e[0])] = (e[1], e[2:])


for key in sorted(result.keys()):
    print(key, result[key])

output:

100 ('Mulan', ['300,500', '200,400'])
200 ('Ariel', ['100,500', '500'])
300 ('Jasmine', ['500', '500,100'])
400 ('Elsa', ['100,500'])
500 ('Belle', ['200,300'])

I know this is not quite your output. But as I said: you can work from here if these empty lists are not important.

Tuples, The values stored in a tuple can be any type, and they are indexed by integers. so we can sort lists of them and use tuples as key values in Python dictionaries. import string fhand = open('romeo-full.txt') counts = dict() for line in fhand: line At the end we write a nice for loop which does a multiple assignment iteration  I'm trying to read a text file and then create a dictionary using the data in that file. An example of the text would be: 100 Mulan 300, 500 200, 400 200 Ariel 100, 500 500 300 Jasmine 500 500,


A solution similar to Maik Kahnt's, it also includes the empty list for Elsa and also depends on having 5 lines for each record.

from pprint import pprint

fin = open('f2.txt', 'r')

array = []
dict_ = {}

lines = fin.readlines()

for i, line in enumerate(lines):
    line = line.rstrip()
    if i % 5 == 0:
        key = int(line)
    elif i % 5 == 1:
        name = line
    elif i % 5 == 2:
        if len(line):
            rec = [int(j) for j in line.split(', ')]
        else:
            rec = []
        array.append(rec)
    elif i % 5 == 3:
        if len(line):
            rec = [int(j) for j in line.split(', ')]
        else:
            rec = []
        array.append(rec)
        dict_[key] = (name, *array)
        array = []

pprint(dict_)

Output was:

{'100': ('Mulan', [300, 500], [200, 400]),
 '200': ('Ariel', [100, 500], [500]),
 '300': ('Jasmine', [500], [500, 100]),
 '400': ('Elsa', [100, 500], []),
 '500': ('Belle', [200, 300], [100, 200, 300, 400])}

20. Dictionaries, The key:value pairs of the dictionary are separated by commas. You also might wonder why we use dictionaries at all when the same concept of mapping a key to a value could Lists, tuples, and strings have been called sequences, because their items Such a frequency table might be useful for compressing a text file. Associating Multiple Values with Each Key in a Dictionary Credit: Michael Chermside Problem You need a dictionary that maps each key to multiple values. Solution By nature, a dictionary is … - Selection from Python Cookbook [Book]


We can define helper functions to do the string and data manipulation, and just populate the dictionary with in a simple loop. The following does just that. Note, you can change newline appropriately for your platform

def normalise(value):
    if value.isalpha():
        return value
    if value.isnumeric():
        return int(value)
    return [int(i) for i in value.replace(",", "").split()]

def normalise_value(lst):
    xs = [[i] if isinstance(i, int) else i for i in lst]
    while len(xs) < 3:
        xs.append([])  # gets the empty list as needed
    return tuple(xs)

def strip_newline(string, newline="\n"):
    return string.replace(newline, "")

Now the actual data processing code:

with open("filename") as fh:
    lines = fh.readlines()

newline = "\n"  # set as appropriate
data = []
dct = {}        
for d in lines:
    if d is not newline:
        data.append(normalise(strip_newline(d)))
    elif data:
        dct[data[0]] = tuple(normalise_value(data[1:]))
        data = []
if data:
    dct[data[0]] = tuple(normalise_value(data[1:]))

Learn to Program using Python: Using Tuples as Keys, Overwrites an existing string value in the dictionary with a tuple value. Although Python code is not written using boldface, I typically use print "Key",' : ',"Value" for x in d1.keys():print x,' : ',d1[x] print ""# Print blank line Listing 1 Richard has participated in numerous consulting projects involving Java,  A Python program can read a text file using the built-in open() function. For example, below is a Python 3 program that opens lorem.txt for reading in text mode, reads the contents into a string variable named contents, closes the file, and then prints the data.


It is your fellow student at UTM, taking the exact same course and currently working on this very assignment. Let me tell you a couple things:

  1. Professors and TAs do have a StackOverflow account(s) and they will catch you!
  2. Posting assignment questions and asking for answers is an academic offence and you will definitely get called into your instructor's office to explain why they found an assignment question on StackOverflow! If it is available on the internet, either the TAs or the Instructors will surely find it and catch you.

Well just so you know:

  1. Doing this will in no shape or form help you understand the concepts for the final exam which is soon!

To sum up, you can anything in this world, but note that some things you decide to do aren't the right or the most honest thing you can do.

Dictionary Data Structures in Python 3, Dictionaries map keys to values, making key-value pairs that can then store data. isolates values; dict.items() returns items in a list format of (key, value) tuple pairs within the sammy dictionary and printed out the keys and values line by line, If we use the usernames dictionary later in our program file, it will include the  mdict is a subclass of the built-in dictionary in which each key maps to a list of values. By overriding __setitem__, it changes the behavior of both the get method and the [ ] operator. If d is a normal dictionary, then d[key]=value replaces the old value for the given key, if there is one.


Python, Below are various methods to convert dictionary to list of tuples. Python code to convert dictionary into list of tuples listt = zip ( dict .keys(), dict .values()). Return multiple values. This is an age-old problem. A method may need to return many things, not just one. A tuple can return multiple values (with less code than a class would require). Note: This causes an allocation. Using ref and out parameters would be faster for a method that is hot. Parameters. Note 2: A Tuple has advantages. It is a


Dictionaries in Python – Real Python, Defining a Dictionary; Accessing Dictionary Values; Dictionary Keys vs. Take the Quiz: Test your knowledge with our interactive “Python Dictionaries” quiz. A list of tuples works well for this: MLB_team['Toronto'] Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> MLB_team['Toronto'] KeyError:​  The new list is sorted in ascending alphabetical order by the key value. 10.5 Multiple assignment with dictionaries Combining items, tuple assignment and for, you can see a nice code pattern for traversing the keys and values of a dictionary in a single loop: for key, val in d.items(): print val, key


Lesson 6, In python, the word is called a 'key', and the definition a 'value'. You give your tuple a name, then after that the list of values it will carry. Note that the '\' thingy at the end of sthurlow.comthe first line carries over that line of a list or dictionary (An entry in a dictionary is just a variable with a number or text string as a name. each line in the text will have a username, first name, last name, age, gender and an e-mail address. The function will insert each person's information into a dictionary with their username as the key, and the value being a list of [last name, first name, e-mail, age, gender]. basically what im trying to do is open a text file that contains this: