logo
down
shadow

Reading excel column 1 into Python dictionary key, column 2 into value


Reading excel column 1 into Python dictionary key, column 2 into value

By : Jaeger Favian
Date : December 01 2020, 05:00 PM
I hope this helps . I have an excel sheet containing the following: , You can use the xlrd module as follows:
code :
import xlrd

workbook = xlrd.open_workbook(r"input.xlsx")
sheet = workbook.sheet_by_index(0)

col_a = sheet.col_values(0, 1)
col_b = sheet.col_values(1, 1)

my_dict = {a : b for a, b in zip(col_a, col_b)}

print my_dict
{u'A': 1.0, u'C': 3.0, u'B': 2.0, u'D': 4.0}


Share : facebook icon twitter icon
Return a dictionary in excel using a csv for each column in Python

Return a dictionary in excel using a csv for each column in Python


By : Brian
Date : March 29 2020, 07:55 AM
this will help If I understood your question you want to create a dict that the keys are the headings of your file. And each key hold a list with the column content as items. To do so, your code can be like this:
code :
import csv


def read_csv(filename, col_list):
    """This function expects the name of a CSV file and a list of strings
    representing a subset of the headers of the columns in the file, and
    returns a dictionary of the data in those columns, as described below."""

    with open(filename, 'r') as f:
        # Better covert reader to a list (items represent every row)
        reader = list(csv.DictReader(f))
        dict1 = {}
        for col in col_list:
            dict1[col] = []
            # Going in every row of the file
            for row in reader:
                # Append to the list the row item of this key
                dict1[col].append(row[col])

    return dict1


print(read_csv(filename='words.csv', col_list=['happy', 'sad']))
{'sad': ['abominable', 'abominably', 'abominate', 'abomination', 'abort', 'aborted', 'aborts', 'abrade', 'abrasive', 'abrupt', 'abruptly', 'abscond', 'absence', 'absent-minded', 'absentee', 'absurd', 'absurdity', 'absurdly', 'absurdness', 'abuse', 'abused', 'abuses', 'abusive', 'abysmal', 'abysmally', 'abyss', 'accidental', 'accost', 'accursed', 'accusation', 'accusations', 'accuse', 'accuses', 'accusing', 'accusingly', 'acerbate', 'acerbic', 'acerbically', 'ache', 'ached', 'aches', 'aching', 'acrid', 'acridly', 'acridness', 'acrimonious', 'acrimoniously', 'acrimony', 'adamant', 'adamantly', 'addict', 'addicted', 'addicting', 'addicts', 'admonish', 'admonisher', 'admonishingly', 'admonishment', '', 'OF', 'WELL-BEING', 'ASSURANCE', 'A', 'REASON', 'FOR', 'BEING', 'ACARONAR', 'ACCOMMODATIVE', 'ALTITUDINARIAN', 'AMAZING', 'WORDS', 'AMIABLY', 'ACCOLADE', 'ACUMEN', 'ADJUSTABLE', 'ADMIRER', 'ADMIRING', 'ADMIRINGLY', 'ADORER', 'ADROIT', 'ADROITLY', 'ADULATED', 'ADULATION', 'ADULATORY', 'ADVENTURESOME', 'ADVOCATED', 'AMBITIOUS', 'AMBITIOUSLY', 'AMELIORATE', 'AMENITY', 'AMITY', 'AMPLY', 'AMUSE', 'AMUSINGLY', 'APOTHEOSIS', 'ASSUME', 'YOUR', 'OWN', 'VALUE', 'ASTONISHINGLY', 'ASTONISHMENT', 'ATTRIBUTIONAL', 'STYLE', 'QUESTIONNAIRE', '(ASQ)', 'AUTHENTIC', 'HAPPINESS', 'AWAKEN', 'AWAKENING', ''], 'happy': ['ADORED', 'ADORING', 'ADORINGLY', 'ADVANCED', 'ADVANTAGEOUS', 'ADVANTAGEOUSLY', 'ADVANTAGES', 'AFFABILITY', 'AFFABLY', 'AFFINITY', 'AFFIRMATION', 'AFFIRMATIVE', 'AFFLUENCE', 'AFFLUENT', 'AFFORD', 'AFFORDABLE', 'AFFORDABLY', 'AGILE', 'AGILELY', 'AGREEABLENESS', 'AGREEABLY', 'ALIGNED', 'ALL', 'IS', 'WELL', 'ALLURING', 'ALLURINGLY', 'ALTERNATIVE', 'HEALING', 'ALTRUISTICALLY', 'AMAZE', 'AMAZEMENT', 'AMAZES', 'AMAZINGLY', 'AMIABILITY', 'AMICABILITY', 'AMICABLE', 'AMICABLY', 'AMUSING', 'APPEAL', 'APPEALING', 'APPLAUD', 'APPRECIABLE', 'APPRECIATED', 'APPRECIATES', 'APPRECIATION', 'OF', 'BEAUTY', 'APPRECIATIVELY', 'APPROPRIATE', 'APPROVAL', 'APPROVE', 'ARDOR', 'ART', 'OF', 'APPRECIATION', 'ART', 'OF', 'STILLNESS', 'ART', 'OF', 'WELL-BEING', 'ASSURANCE', 'A', 'REASON', 'FOR', 'BEING', 'ACARONAR', 'ACCOMMODATIVE', 'ALTITUDINARIAN', 'AMAZING', 'WORDS', 'AMIABLY', 'ACCOLADE', 'ACUMEN', 'ADJUSTABLE', 'ADMIRER', 'ADMIRING', 'ADMIRINGLY', 'ADORER', 'ADROIT', 'ADROITLY', 'ADULATED', 'ADULATION', 'ADULATORY', 'ADVENTURESOME', 'ADVOCATED', 'AMBITIOUS', 'AMBITIOUSLY', 'AMELIORATE', 'AMENITY', 'AMITY', 'AMPLY', 'AMUSE', 'AMUSINGLY', 'APOTHEOSIS', 'ASSUME', 'YOUR', 'OWN', 'VALUE', 'ASTONISHINGLY', 'ASTONISHMENT', 'ATTRIBUTIONAL', 'STYLE', 'QUESTIONNAIRE', '(ASQ)', 'AUTHENTIC', 'HAPPINESS', 'AWAKEN', 'AWAKENING']}
I want to display a column of Excel in the form of a dictionary in python

I want to display a column of Excel in the form of a dictionary in python


By : Hagen Lindbergh
Date : March 29 2020, 07:55 AM
it helps some times Install the openpyxl package (if you don't have it already), and then do:
code :
import openpyxl

# Access active worksheet of excel file
book = openpyxl.load_workbook('workbook.xlsx')
sheet = book.active

# Access first column
column = sheet['A']

# Use dictionary comprehension on the cells in the column
d = {
    'item{}'.format(num): cell.value
    for (num, cell) in enumerate(column, 1)
}
Transform dictionary into one column of a dataframe while keeping the dictionary row names in another column (python)

Transform dictionary into one column of a dataframe while keeping the dictionary row names in another column (python)


By : daveC
Date : March 29 2020, 07:55 AM
Any of those help I have several dictionaries which I would like to transform into dataframes. , Use list comprehension with flatten dictionary to list of tuples:
code :
df = pd.DataFrame([(x, k) for k, v in example_d.items() for x in v], 
                   columns = ['value','R_value'])
print (df)
    value R_value
0       1      R1
1       2      R1
2       3      R1
3       4      R1
4       5      R2
5       6      R2
6       7      R2
7       8      R2
8      10      R3
9      10      R3
10     10      R3
11     10      R3
df = pd.Series(example_d).explode().reset_index()
df.columns = ['R_value','value']
print (df)
   R_value value
0       R1     1
1       R1     2
2       R1     3
3       R1     4
4       R2     5
5       R2     6
6       R2     7
7       R2     8
8       R3    10
9       R3    10
10      R3    10
11      R3    10
How to write an excel file which has dictionary keys as column name and dictionary values as column values?

How to write an excel file which has dictionary keys as column name and dictionary values as column values?


By : shahzeb
Date : March 29 2020, 07:55 AM
I hope this helps . I have a dictionary as follows: , You can do this using pandas module
code :
import pandas as pd

x = [{'tarih': '01.02.2019', '4980': 1.1517482514, '2738': 0.9999999999999999, '0208': 1.0102518747365854},{'tarih': '02.02.2019', '4980': 1.1517486767, '2738': 0.9999999999999999, '0208': 1.0102518747368554}]

df = pd.DataFrame(x)

df.to_excel ('test.xlsx', sheet_name = 'sheet1', index = False)
     tarih      4980        2738    0208
0   01.02.2019  1.151748    1.0    1.010252
1   02.02.2019  1.151749    1.0    1.010252
reading a column from excel and parsing into dictionary key value python

reading a column from excel and parsing into dictionary key value python


By : stk_usr
Date : March 29 2020, 07:55 AM
this one helps. I have one of the columns in excel as following: , Step 1:
Related Posts Related Posts :
  • How to parse HTML table with rows contaning both <th> and <td> tags under the <tr> tag?
  • Using recursion with map in python
  • Creating lists with loops in Python
  • I have a program to check if five numbers are prime but it is not working correctly
  • Returned answer wrong in pyschool Topic 2: Q 6
  • What are the centroid of k-means clusters with PCA decomposition?
  • How do mongoengine filter field not null?
  • Categorize results based on Model in haystack?
  • Error installing pycrypto on my mac
  • Can Django ORM has strip field?
  • Python pack / unpack converts to Objective C
  • Python - Selenium Locate elements by href
  • Couldn't iterate over a dictionary context variable in template, despite having all in place, as far as I know?
  • Test if Django ModelForm has instance on customized model
  • AttributeError: 'module' object has no attribute 'timeit' while doing timeit a python function
  • Accessing button using selenium in Python
  • Removing White Spaces in a Python String
  • Sort timestamp in python dictionary
  • How to use Python 2 packages in Python 3 project?
  • retrieve links from web page using python and BeautifulSoup than select 3 link and run it 4 times
  • applying lambda to tz-aware timestamp
  • Having two Generic ListViews on the same page
  • Merging numpy array elements using join() in python
  • pythonic way to parse/split URLs in a pandas dataframe
  • Added iterating over page id in Scrapy, responses in parse method no longer run
  • wanting to add an age gate to my quiz
  • Removing top empty line when writing a text file Python
  • How to use a template html in different folder on Google App Engine python?
  • Access ndarray using list
  • unable to post file+data using python-requests
  • How to test aws lambda functions locally
  • inconsistent plot between matplotlib and seaborn in Python
  • How matplotlib show obvious changes?
  • Project in Python3, reading files, word data
  • Check for specific Item in list without Iteration or find()
  • Unicode encoding when reading from text file
  • Overloaded variables in python for loops?
  • All elements have same value after appending new element
  • Python Threading loop
  • `_pickle.UnpicklingError: the STRING opcode argument must be quoted`
  • Python: How to stop a variable from exceeding a value?
  • python textblob and text classification
  • Django - Context dictionary for attribute inside a class
  • Database is not updated in Celery task with Flask and SQLAlchemy
  • Shapely intersections vs shapely relationships - inexact?
  • How to extract a percentage column from a periodic column and the sum of the column?
  • Zombie ssh process using python subprocess.Popen
  • Python regex to capture a comma-delimited list of items
  • joining string and long in python
  • Value Error in python numpy
  • Check if any character of a string is uppercase Python
  • TensorFlow - why doesn't this sofmax regression learn anything?
  • Python Anaconda Proxy Setup via .condarc file on Windows
  • Creating django objects from emails
  • Get spotify currently playing track
  • Select multiple columns and remove values according to a list
  • Python - How to Subtract a Variable By 1 Every Second?
  • Tkinter unable to alloc 71867 bytes
  • How to add Variable to JSON Python Django
  • CSRF token missing or invalid Django
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co