Tags down


List of lists to dictionary of specific format

By : poineer911
Date : September 12 2020, 04:00 PM
seems to work fine The error you are getting is due to the fact you are trying to set a list as a dictionary key. The following example will reproducer the same results:
code :
>>> d = dict()
>>> d[['a', 'b']] = 123
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    d[['a', 'b']] = 123
TypeError: unhashable type: 'list'
{ ['a','b']: 2, 
  ['c','d']: 2, 
  ['a','b','c']: 3
import inflect
p = inflect.engine()

new_list = list()
count = 1
already_used_labels = set()

# The nested loop...
for inner_list in l:
    for label in inner_list:
        if label in already_used_labels:
        new_list.append({'data': {'id': p.number_to_words(count), 'label': label}})
        count += 1
 {'data': {'id': 'one', 'label': 'a'}}, 
 {'data': {'id': 'two', 'label': 'b'}},
 {'data': {'id': 'three', 'label': 'c'}}, 
 {'data': {'id': 'four', 'label': 'd'}}

Share : facebook icon twitter icon

Convert python list of lists into dictionary format

By : Vinayak Nanda
Date : March 29 2020, 07:55 AM
may help you . That's pretty simple. The dict constructor already accepts an iterable of two-element-iterables. The only extra difficulty here is that your keys and values are in reverse order.
code :
>>> mylist = [[14.76, u'2017-10-11T06:00:00Z'], [14.75, u'2017-10-11T07:00:00Z'], [14.21, u'2017-10-11T08:00:00Z']]
>>> dict(map(reversed, mylist))
{u'2017-10-11T07:00:00Z': 14.75, u'2017-10-11T06:00:00Z': 14.76, u'2017-10-11T08:00:00Z': 14.21}*

create nested dictionary from specific elements of 2 list of lists

By : M. Shif
Date : March 29 2020, 07:55 AM
help you fix your problem The trouble you're running into here is that dict() (and dictionary comprehensions as well) will favor the last key-value pair it encounters if it runs into duplicate keys, e.g.:
code :
dict([(1,2), (1,3)]) == {1: 3}
result = {}

for arr, fa in zip(fa_n, serv_n):   
    key = arr[3]

    if key in result:
        result[key][arr[4]] = fa[1]
        result[key] = {arr[4]: fa[1]}

print result

How to filter list lines of a dictionary of lists according to a specific number?

By : Sinan Thottan
Date : March 29 2020, 07:55 AM
wish help you to fix your issue If your lists are already sorted, we can use bisect to find the place between the "Experiencer" and "Status" entries:
code :
from bisect import bisect

l=[(2310, "Experiencer: 'like hours'", 212, 222), (2310, "Experiencer: 'two'", 1035,1038), (2310, "Experiencer: 'Anakin'", 1560, 1566), (2310, "Experiencer: ' '", 1619, 1620), (2310, "Experiencer: 'Tatooine'", 1726, 1734), (2310, "Experiencer: 'Anakin'", 1775, 1781), (2310, "Experiencer: 'Master Qui-Gon'", 1863, 1877), (2310, "Experiencer: 'half'", 1883, 1887), (2310, "Experiencer: 'One'", 2114, 2117), (2310, "Experiencer: 'Anakin'", 2180, 2186), (2310, "Stimulus: 'One'", 2484, 2487), (2310, "Stimulus: 'Anakin'", 2564, 2570), (2310, "Stimulus: 'Padme'", 2739, 2744)]

right_index = bisect(l, (2310, "F"))  # "F" comes between "Experiencer" and "Status" 
lower, higher = l[right_index-1], l[right_index]

print(lower, higher, sep="\n")

# (2310, "Experiencer: 'Anakin'", 2180, 2186)
# (2310, "Stimulus: 'One'", 2484, 2487)
from bisect import bisect

def get_boundary(l):  # This assumes all lists in your dict have at least 2 items
    if len(l) < 2:
        return l
    right_index = bisect(l, (l[0][0], "F"))  
    return [l[right_index-1], l[right_index]]

print({key: get_boundary(value) for key, value in d.items()})
{'hate': [(2310, "Experiencer: 'Anakin'", 2180, 2186), 
          (2310, "Stimulus: 'One'", 2484, 2487)], 
 'confirmation': [(4132, "Experiencer: 'Qui-Gon's'", 4100, 4109), 
                  (4132, "Stimulus: 'Anakin'", 4281, 4287)]

How to Have a dictionary that appends multiple values via list, from another list in specific format

By : Meena Vedam
Date : March 29 2020, 07:55 AM
will be helpful for those in need There are two reasonable ways to go about making a dictionary that contains lists that you add to, rather than single items. The first is to check for an existing value before adding a new one. The second is to use a more sophisticated data structure, that takes care of creating the lists whenever it is necessary.
Here's a quick example of the first approach:

How to return the list of dictionary in specific format in python

By : FreePvp
Date : September 22 2020, 06:00 AM
wish of those help Grouping of elements can be done by itertools.groupby, removing the duplicates by set.
For example:
code :
from pprint import pprint
from itertools import groupby

l = [{'pf': 'ABC', 'src': 'SCI'}, {'pf': 'ABC', 'src': 'MC'}, {'pf': 'ASR', 'src': 'CC'}, {'pf': 'ASR', 'src': 'CC'}, {'pf': 'ASR', 'src': 'ACS'}, {'pf': 'ABC', 'src': 'CC'}, {'pf': 'NS', 'src': 'ATT'}]

out = {'customers': [], 'platform': 'all'}
for v, g in groupby(sorted(l, key=lambda k: k['pf']), lambda k: k['pf']):
    out['customers'].append( {'pf': v, 'src': list(set(val['src'] for val in g))} )

{'customers': [{'pf': 'ABC', 'src': ['MC', 'SCI', 'CC']},
               {'pf': 'ASR', 'src': ['ACS', 'CC']},
               {'pf': 'NS', 'src': ['ATT']}],
 'platform': 'all'}
Related Posts Related Posts :
  • Why is the interpreter call the variable i a local variable
  • Passing multiple list in a function as *args gives a None result
  • Getting a tclerror with PhotoIMage
  • How to efficiently disaggregate data from?
  • Group by the dates to weeks
  • Accuracy problems in estimating pi using Machin's method
  • Printing a list method return None
  • how to make scatter plot of two columns and divide x_axis in 3 column f1,f2,and f3
  • Can I install python 3.7 in ubuntu 18.04 without having python 3.6 in the system?
  • Applying a function to every cell of dataframes
  • Cant install allennlp with pip on mac
  • ModuleNotFoundError: No module named 'virtualenv' Exiting due to failure, even after virtual environment is successfully
  • How to fix " 'int' object is not subscriptable" on this code
  • question about custom sorting using key argument in sorted()
  • Python3-tk is already installed but python3.7 can't find module tkinter
  • Pickle messing up text
  • How to install torch==0.3.1 in python=3.6
  • Tkinter Checkbuttons' values won't change
  • How to call asynchronous functions without expecting returns from them?
  • Unable to convert string to date (Portuguese locale)
  • Use textract on PDF file located on Google Cloud Storage
  • How to fix 'Can't open libmsodbcsql-17.3.so.1.1'
  • Using the join method in python - confusing error
  • Pandas Dataframe to .csv file
  • Tell if an object's attribute has been used
  • Read files from Cloud Storage having definite prefix but random postfix
  • Extract Button link text from a website python selenium
  • Reverse string, but not integers
  • TkFiledialog.askopenfilename() launches a window for "save as" in windows 10
  • Printing last 3 lines of a .csv file
  • I can't install python packages by using pip3 on alpine
  • Setting up a Flask app that uses headed Selenium on a Ubuntu 18.04 LTS Server
  • How to convert month name to month number in a timeseries in DataFrame?
  • Why does pandas.where() returning 'None'
  • How to extract matching keywords from two columns in a pandas dataframe?
  • python converting a List of Tuples into a Dict with external keys
  • How to fix ModuleNotFoundError: No module named 'pip._internal' with python source code installation
  • Pytorch RuntimeError: Expected tensor for argument #1 'indices' to have scalar type Long; but got CUDAType instead
  • Covert a dataframe into a matrix form
  • i am webscraping with bs4 and the urls wont show up
  • docker build: Returned a non-zero code: 5
  • Pandas read_csv from FileStorage in Flask
  • How do I add elements of a set and print their sum?
  • Is there a way to add a column to a geopandas dataframe using a single value geoseries?
  • Issue with appending to an array
  • no module named "tensorflow.python.platform" when importing tensorflow || tflearn on python shell
  • Accesing "Next" page with scrapy rules
  • How to take all combination of a pandas dataframe (choosing 2 at a time) and make a new dataframe with each two combinat
  • Connecting the missing pixels
  • Returns Nothing [] from Google + API using Python
  • pd.DataFrame: adding values in specific locations
  • Validating phone numbers in python using RE
  • How to fetch all data of solr which contains 40k rows into csv?
  • Inheritance of modules in Python?
  • ModuleNotFoundError: No module named 'frontend'
  • Only One Pod is consuming all the computing resource although specified the limits and requests resources in pod templat
  • IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number
  • Scraping 'next' page after finishing in the main one using Rules
  • Add custom headers to SOAP request using zeep.Client Python
  • It the any proper way how to take a two byte elemetns from list, concat them, and convert them to integer
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk