logo
down
shadow

Zipping items from a list with lists from an ordered dictionary in Python


Zipping items from a list with lists from an ordered dictionary in Python

By : user2954846
Date : November 22 2020, 10:33 AM
To fix this issue make a loop ove given_dict.items() and add the elements of given_list with your values !
code :
>>> given_dict = OrderedDict((j[0],j[1]+[given_list[i]]) for i,j in enumerate(given_dict.items()))
>>> given_dict
OrderedDict([('one', ['-', '-', 'a']), ('two', ['-', '-', 'b'])])
>>> given_dict = dict((j[0],j[1]+[given_list[i]]) for i,j in enumerate(given_dict.items()))
>>> given_dict
{'two': ['-', '-', 'b'], 'one': ['-', '-', 'a']}


Share : facebook icon twitter icon
Python - categorizing items in a list based on occurrence in a dictionary of lists

Python - categorizing items in a list based on occurrence in a dictionary of lists


By : tkcas
Date : March 29 2020, 07:55 AM
To fix the issue you can do For an efficient solution you want to avoid explicit loops as much as possible:
code :
items = set(items)
fruits = set(foods_dict['fruit']) & items
veggies = set(foods_dict['veg']) & items
others = items - fruits - veggies
In [5]: %%timeit
   ...: items2 = set(items)
   ...: fruits = set(foods_dict['fruit']) & items2
   ...: veggies = set(foods_dict['veg']) & items2
   ...: others = items2 - fruits - veggies
   ...: 
1000000 loops, best of 3: 1.75 us per loop

In [6]: %%timeit
   ...: fruits = set()
   ...: veggies = set()
   ...: others = set()
   ...: for item in items:
   ...:     if item in foods_dict.get('fruit'):
   ...:         fruits.add(item)
   ...:     elif item in foods_dict.get('veg'):
   ...:         veggies.add(item)
   ...:     else:
   ...:         others.add(item)
   ...: 
100000 loops, best of 3: 2.57 us per loop

In [7]: %%timeit
   ...: veggies = set(elem for elem in items if elem in foods_dict['veg'])
   ...: fruits = set(elem for elem in items if elem in foods_dict['fruit'])
   ...: others = set(items) - veggies - fruits
   ...: 
100000 loops, best of 3: 3.34 us per loop
In [9]: foods_dict = {}
   ...: foods_dict['fruit'] = list(range(0, 10000, 2))
   ...: foods_dict['veg'] = list(range(1, 10000, 2))

In [10]: items = list(range(5, 10000, 13))  #some odd some even

In [11]: %%timeit
    ...: fruits = set()
    ...: veggies = set()
    ...: others = set()
    ...: for item in items:
    ...:     if item in foods_dict.get('fruit'):
    ...:         fruits.add(item)
    ...:     elif item in foods_dict.get('veg'):
    ...:         veggies.add(item)
    ...:     else:
    ...:         others.add(item)
    ...: 
10 loops, best of 3: 68.8 ms per loop

In [12]: %%timeit
    ...: veggies = set(elem for elem in items if elem in foods_dict['veg'])
    ...: fruits = set(elem for elem in items if elem in foods_dict['fruit'])
    ...: others = set(items) - veggies - fruits
    ...: 
10 loops, best of 3: 99.9 ms per loop

In [13]: %%timeit
    ...: items2 = set(items)
    ...: fruits = set(foods_dict['fruit']) & items2
    ...: veggies = set(foods_dict['veg']) & items2
    ...: others = items2 - fruits - veggies
    ...: 
1000 loops, best of 3: 445 us per loop
Zipping lists within a list in Python

Zipping lists within a list in Python


By : 9D01X
Date : March 29 2020, 07:55 AM
it helps some times I have a list of lists , Use the *args argument expansion syntax:
code :
zip(*big_list)
>>> big_list = [['a1','b1','c1'], ['a2','b2','c3'], ['a3','b3','c3']]
>>> zip(*big_list)
[('a1', 'a2', 'a3'), ('b1', 'b2', 'b3'), ('c1', 'c3', 'c3')]
Python: Zipping multiple lists into a dictionary

Python: Zipping multiple lists into a dictionary


By : user2186863
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Ok, so I have 6 lists taken from a csv file that I want to create a dictionary from, with one list being the key value and the other 5 each containing a value attached to that key. I them am deleting certain rows if their keys match a value in a 7th list (c6). Any help is appreciated, write now I'm stuck getting the lists to populate from the correct column of the csv. I also have a messy amount of readers since they can only be looped through once.
code :
with open (r'filea', 'r', newline='') as f:

    data = {}
    exclude = set()

    for row in csv.reader(f, delimiter=','):
        data[row[0]] = row[1:6]
        exclude.add(row[6])

    for key in exclude:
        if key in data:
            del data[key]

    with open (r'fileb', 'w', newline='') as g:
        wrt=csv.writer(g)
        # do the writing
Python: Sending a dictionary's items to a list of lists

Python: Sending a dictionary's items to a list of lists


By : Kewal Kulkarni
Date : March 29 2020, 07:55 AM
I wish this help you Assuming you have the dictionary Dd. You want to prepare a list of lists with key and value pair we can make use of comprehensions.
Here is the one line solution:
code :
[ [x,y] for x in Dd.keys() for y in Dd.values() if Dd[x] == y ]
[[x, y] for x, y in Dd.items()]
Zipping a Python Dictionary and List together

Zipping a Python Dictionary and List together


By : MRFrankJ Producer Fr
Date : March 29 2020, 07:55 AM
I hope this helps . Is it possible to Zip a python Dictionary and List together? , You can use iteritems().
code :
dictionary = {'A':1, 'B':2, 'C':3}
num_list = [1, 2, 3]
zipped = zip(dictionary.iteritems(), num_list)

for (key, value), num_list_entry in zipped:
    print key
    print value
    print num_list_entry
Related Posts Related Posts :
  • Read data with NAs into python and calculate mean row-wise
  • How to print telnet response line by line?
  • Pylint: Avoid checking INSIDE DOCSTRINGS (global directive / rcfile)
  • Sending MIDI messages using Python (on Ubuntu)
  • Generate Dictionary in Python at run time
  • code is cluttered by try-except in Python
  • Python class inheritance - spooky action
  • Why is a Python multiprocessing daemon process not printing to standard output?
  • How to feed numeric data into a classifier?
  • How to unambiguously identify a Model as a lowercase string in Django
  • How to get only one specific line from subprocess output
  • Python network communication with encryption and password protection
  • with urllib urlopen read function but get none
  • django could not find database in ubuntu
  • How to replace a character in a string with a non ascii character in python?
  • Self learning data evaluation in Python
  • Django: UnicodeDecodeError while trying to read template 500.html
  • how can you Import an os variable into PYTHON and have it update?
  • Browse Folders to open a file in python
  • sql select group by a having count(1) > 1 equivalent in python pandas?
  • Why Insert command when button clicked OpenERP
  • Pandas dataframe from nested dictionary to melted data frame
  • Which is more efficient in Python: list.index() or dict.get()
  • Xor bits in python
  • A simple python confusion about format string
  • Finding index of a list containing an item, also in a list
  • How to test Domain is it 'www' domain or subdomain or name server domain or mail domain in python?
  • Keydown event for Pygame
  • Lazy loading csv with pandas
  • Use webdriver,python,beautifulsoup to retrieve dynamic website
  • Scrapy is Visiting same Url despite dont_filter=False
  • How to add support for SNI in python 2.7
  • Pandas: np.where with multiple conditions on dataframes
  • How to get meaningful words by splitting a continuous string?
  • TypeError: 'numpy.ndarray' object is not callable while extracting index and elements are stored in different array in p
  • Python: comparing list to a string
  • Is there any way to write '\r' into a file on linux with python?
  • matplotlib retrieve color from plt.plot command
  • Scrapy JSON export issues
  • beautifulsoup to retrieve the date
  • Django Rest Framework 3.0: Saving Nested, Many-To-One Relationship
  • Lost connection to MySQL server during Python connection
  • uploadede file path django
  • How to reduce a data with the longest string under pandas framework?
  • Single line for-loop to build a dictionary?
  • How to read in lines until a certain line?
  • Beautifulsoup to retrieve the href list
  • Python - Vincenty's inverse formula not converging (Finding distance between points on Earth)
  • Saving django model instance into another model
  • Same URL request fails with python->urllib but not with curl
  • Python dictionary: set value as the key string
  • With setuptools, when does namespace packages __init__.py files disappears?
  • Paraview: NameError: name 'inputs' is not defined
  • Too many values to unpack during template rendering
  • A different type of iterative function
  • Test if value exists in several lists
  • Go and Python HMAC libraries give different results
  • Python Nested Loop Working Weirdly
  • Why is this not assigning the correct value?
  • 'numpy.ndarray' object is not callable
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org