Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8591027
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T23:25:54+00:00 2026-06-11T23:25:54+00:00

I am a Python beginner who is trying to get multiple random lines for

  • 0

I am a Python beginner who is trying to get multiple random lines for a given category. The original file has three columns, but what I am interested is just one of those categories. The file(csv) looks like this:

   No,Size,Name
   10,1346,Cat
   24,423,Dog
   289,590,Cat
   12,302,Dog
   351,33,Cat
   51,812,Dog
   91,778,Cat
   1193,465,Cat
   44,178,Dog

None of the lines are identical and I want to get random 3 lines for each ‘Name’. This is what I have so far:

import random

with open('C:\Users\Owl\file.csv') as f:
    lines = f.readlines()[1:] #Skip heading

for line in lines:
    try:
        name = line[2]
    except:
        continue

for name in lines:
    for lines in random.sample(lines,3):
        print lines

f.close()

But I get something like this:

   12,302,Dog
   1193,465,Cat
   10,1346,Cat
   2
   3
   D

instead of something like this:

   1193,465,Cat
   10,1346,Cat
   91,778,Cat
   51,812,Dog
   44,178,Dog
   12,302,Dog

In the output I get now, I am not getting lines by ‘Name’ and somehow just letters/numbers after that. Then, I get “ValueError: sample larger than population” and terminates (actual file is much larger than the example here).

Also, if possible, is there an easy way to sort by “Name” in the output?

I have been struggling with this for hours looking it up on the Internet but have not been able to solve… Could anybody please help me? Thank you all!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T23:25:55+00:00Added an answer on June 11, 2026 at 11:25 pm

    You can do this much more easily by using itertools.groupby() and the csv module. We first make a csv.DictReader to give us easy access to the values, we then sort and group the list by the "Name" column, and then select the values.

    import itertools
    import csv
    import operator
    import random
    
    with open("test.csv") as file:
        data = csv.DictReader(file)
        key = operator.itemgetter("Name")
        for name, items in itertools.groupby(sorted(data, key=key), key):
            print(name+":", random.sample(list(items), 3))
    

    Which gives us:

    Cat: [{'Size': '33', 'Name': 'Cat', 'No': '351'}, {'Size': '590', 'Name': 'Cat', 'No': '289'}, {'Size': '465', 'Name': 'Cat', 'No': '1193'}]
    Dog: [{'Size': '178', 'Name': 'Dog', 'No': '44'}, {'Size': '812', 'Name': 'Dog', 'No': '51'}, {'Size': '302', 'Name': 'Dog', 'No': '12'}]
    

    If you wish to make the dictionaries lists, it’s easy to do with a simple list comprehension:

    [[item["No"], item["Size"], item["Name"]] for item in items] 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Python beginner here. I have a text file that is sorted into columns: fields
I am quite a beginner to Python and trying to get my head around
I'm trying to get simple code working, unfortunately I'm a python beginner. My script
I am a beginner in Python. My data table (Table1) has 21 columns and
I am beginner python prorammer. With 2.7.2, Windows 7, built-in interpreter, and three libraries.
Python beginner >>> import oauth2 Traceback (most recent call last): File , line 1,
I'm a beginner in python and I'm trying to use a octal number in
I am a beginner at Python, and to those who holds negative thoughts against
Python beginner, I have become familiar with reading through a file and doing basic
I am a python beginner and I am trying to average two NumPy 2D

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.