logo
down
shadow

How do I delete keys from a dictionary that are shorter than a certain length in python?


How do I delete keys from a dictionary that are shorter than a certain length in python?

By : Ruben Tammaro
Date : November 19 2020, 03:01 PM
will be helpful for those in need Use Dictionary comprehensions. No need to do for k in d.keys(). Just use for k in d as d.keys() will return a list which is not needed at all. (A lesson I learnt from Stackoverflow itself!!)
Also as @roganjosh pointed out use len() instead of len[] (len() is a function). Square brackets are used for indexing in say, lists and strings.
code :
d={'longggg':'a', 'short':'b', 'medium':'c', 'shor':'d'}

a = {k:d[k] for k in d if len(k)>=6}
print a
{'medium': 'c', 'longggg': 'a'}


Share : facebook icon twitter icon
python delete those keys from dictionary who has same value

python delete those keys from dictionary who has same value


By : Riccardo Masi
Date : March 29 2020, 07:55 AM
like below fixes the issue Hey I have dictionary like following one , You can use set and a dict comprehension:
code :
>>> dicts = {'met_293': ['81.0175','4','7','7','29.76','23','1','0','22','28.57','2','[KG]EHY'],'met_394': ['79.9579','4','7','7','29.76','18','3','0','15','28.57','2','EHY[ILV]'],'met_309': ['81.0175','4','7','7','29.76','23','1','0','22','28.57','2','[KG]EHY'],'met_387': ['79.9579','4','7','7','29.76','18','3','0','15','28.57','2','EHY[ILV]']}
>>> seen = set()
>>> {k:v for k,v in dicts.iteritems() 
                                 if v[11] not in seen and not seen.add(v[11])}
{'met_394': ['79.9579', '4', '7', '7', '29.76', '18', '3', '0', '15', '28.57', '2', 'EHY[ILV]'],
 'met_293': ['81.0175', '4', '7', '7', '29.76', '23', '1', '0', '22', '28.57', '2', '[KG]EHY']}
>>> dic = {}
>>> seen = set()
>>> for k,v in dicts.iteritems():
...     if v[11] not in seen:
...         dic[k] = v
...         seen.add(v[11])
...         
>>> dic
{'met_394': ['79.9579', '4', '7', '7', '29.76', '18', '3', '0', '15', '28.57', '2', 'EHY[ILV]'],
 'met_293': ['81.0175', '4', '7', '7', '29.76', '23', '1', '0', '22', '28.57', '2', '[KG]EHY']}
How to get keys from nested dictionary of arbitrary length in Python

How to get keys from nested dictionary of arbitrary length in Python


By : Tom
Date : March 29 2020, 07:55 AM
Any of those help Use a mix of iteration and tail recursion. After quoting undefined names, making spacing uniform, and removing 'k2' from the first result, I came up with the code below. (Written and tested for 3.4, it should run on any 3.x and might on 2.7.) A key thing to remember is that the iteration order of dicts is essentially random, and varies with each run. Recursion as done here visit sub-dicts in depth-first rather than breadth-first order. For dict0, both are the same, But if dict4 were nested in dict2 rather than dict3, they would not be.
code :
dict0 = {'k0': 0, 'k1': 1, 'dict2':{'k3': 3, 'k4': 4},
         'dict3':{'k5': 5, 'dict4':{'k6': 6}}}

def keys(dic, klist=[]):
    subdics = []
    for key in sorted(dic):
        val = dic[key]
        if isinstance(val, dict):
            subdics.append(val)
        else:
            klist.append(key)
    for subdict in subdics:
        keys(subdict, klist)
    return klist

result = keys(dict0)
print(result, '\n', result == ['k0','k1','k3','k4','k5','k6'])

def keylines(dic, name='outer_dict', lines=[]):
    vals = []
    subdics = []
    for key in sorted(dic):
        val = dic[key]
        if isinstance(val, dict):
            subdics.append((key,val))
        else:
            vals.append(key)
    vals.extend(pair[0] for pair in subdics)
    lines.append('{}_keys = {}'.format(name, vals))
    for subdict in subdics:
        keylines(subdict[1], subdict[0], lines)
    return lines

result = keylines(dict0)
for line in result:
    print(line,)
print()
expect = [
        "outer_dict_keys = ['k0', 'k1', 'dict2', 'dict3']",
        "dict2_keys = ['k3', 'k4']",
        "dict3_keys = ['k5', 'dict4']",
        "dict4_keys = ['k6']"]
for actual, want in zip(result, expect):
    if actual != want:
        print(want)
        for i, (c1, c2) in enumerate(zip(actual, want)):
            if c1 != c2:
                print(i, c1, c2)
how to update a python dictionary by using the keys of arbitrary length?

how to update a python dictionary by using the keys of arbitrary length?


By : Ren
Date : March 29 2020, 07:55 AM
wish of those help I am using python 2.4 to update a dictionary which is very complex and maybe unknown, and the keys is complex but explicit. for example, the dictionary is : , Consider
code :
>>> def get_nested(d, keys):
...     return reduce(dict.get, [d] + keys)
... 
>>> def set_nested(d, keys, value):
...     get_nested(d, keys[:-1])[keys[-1]] = value
... 
>>> dict1 = {
...   'server' : {
...     'index' : 0,
...     'info' : {
...       'ip' : '127.0.0.1',
...       'user' : {
...         'number' : 1001,
...         'tel' : '123456'
...       }
...     }
...   }
... }
>>> 
>>> keys = 'server-info-user-number'.split('-')
>>> get_nested(dict1, keys)
1001
>>> set_nested(dict1, keys, 2555)
>>> dict1
{'server': {'info': {'ip': '127.0.0.1', 'user': {'tel': '123456', 'number': 2555}}, 'index': 0}}
Python: From dictionary to csv with replicating keys by the length of values

Python: From dictionary to csv with replicating keys by the length of values


By : user2570889
Date : March 29 2020, 07:55 AM
wish helps you I hava following dictionary: , Just using DataFrame constructor then stack
code :
s=pd.DataFrame(list(dict_item.values()),index=dict_item.keys()).stack().reset_index(level=0)
s.columns=['item_number','items']
s
Out[609]: 
  item_number   items
0       item1     bag
1       item1   phone
2       item1  laptop
0       item2    sofa
1       item2      TV
2       item2     bed
3       item2    door
4       item2  window
would there be a more shorter version for finding keys from dictionary?

would there be a more shorter version for finding keys from dictionary?


By : Ted Cook
Date : March 29 2020, 07:55 AM
Does that help You can use a comprehension. However, I recommend reading this article. Sometimes because comprehensions are cool, we tend to over use them.
Try the following:
code :
return ''.join(key for key, value in codebook.items() for code in refined_code if value == code)
Related Posts Related Posts :
  • How to exit/terminate a job earlier and handle the raised exception in apscheduler?
  • python, print intermediate values while loop
  • python to loop over yaml config
  • D3.js is not recognized by PyCharm
  • Access the regularization paths obtained from ElasticNetCV in sklearn
  • Pattern table to Pandas DataFrame
  • Get the earliest date from a column (Python Pandas) after csv.reader
  • Get SystemError: Parent module '' not loaded, cannot perform relative import when trying to import numpy in a Cython Ext
  • Bash or Python : Append and prepend a string recursively in all .tex files
  • Changing a certain index of boolean list of lists change others, too
  • complex dataframe filtering request on the last occurence of a value in Panda/Python [EDIT]
  • How to repeatedly get the contents of a Text widget every loop with tkinter?
  • How to call the tornado.queues message externally
  • How can I use regex in python so that characters not included are disallowed?
  • Discarding randmly scattered empty spaces in pandas data frame
  • Get sums grouped by date by same column filtered by 2 conditions
  • Element disappears when I add an {% include %} tag inside my for loop
  • Django Rest Framework with either a slug or a pk lookup field for the DetailAPIView
  • Flask doesn't stream on Lambda
  • Generate all permutations of fixed length where the elements come from two different sets
  • Making function for calculating distance
  • How to handle multiprocessing based on the limit of CPU's
  • Django - static files is not working
  • Remove x axis and y axis black lines with matplotlib
  • tkinter: assigning multiple functions to one button
  • flask-jwt-extended: Fake Authorization Header during testing (pytest)
  • Setting pandas dataframe value based on row and column conditions
  • swig char ** as a pointer to a char *
  • Confusion over `a` and `b` attributes from scipy.stats.uniform
  • How can I do groupy.apply() without sort my index?
  • Querying Google Cloud datastore with ancestor not returning anything
  • Read value from one thread in Python: queue or global variable?
  • Django - context process query being repeated 102 times
  • Convert a list of images and labels to np array to train tensorflow
  • Lambda not supporting NLTK file size
  • Numpy ndarray image pixel mean for pixel values greater than zero: Normalizing image
  • Understanding output of np.corrcoef for two matrices of different sizes
  • Finding longest perfect match between two strings
  • what is wrong with my cosine similarity? Tensorflow
  • How to manage user content in django?
  • Receiving unsupported operand error while comparing random number and user input.
  • How to wrap the process of creating start_urls in scrapy?
  • How to mark 'duplicated sequence' in pandas?
  • Boolean indexing on multidimensionnal array
  • Unmodified column name index in patsy
  • Cleaner way to unpack nested dictionaries
  • Importing a python module to enable a script to be run from command line
  • Maya Python read and set optionMenu value via variable
  • How can I bind a property to another property in Kivy?
  • Python extracting specific line in text file
  • How to implement n-body simulation with pymunk?
  • Python / matplotlib: print to resolution and without white space / borders / margins
  • Sum up the second value from one dictionary with all values from another dictionary
  • Robot Framework: Open a chrome browser without launching URL
  • Generate inline Bokeh scatterplots in Jupyter using a for loop
  • Group list of dictionaries python
  • Efficient way to apply multiple Boolean mask to set values in a column using pandas
  • Lazy evaluation of a Python dictionary
  • id of xpath is getting changed every time in selenium python 2.7 chrome
  • Matplotlib RuntimeWarning displaying a 3D plot
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org