logo
down
shadow

How to set all values of a complex dict to the same one?


How to set all values of a complex dict to the same one?

By : NJK
Date : November 14 2020, 04:51 PM
Hope this helps Give a very complex dict dict_a, i.e., some key corresponses to simple value (level-1), but others many corresponse to another dict (level-n). , Simple recursive function should work:
code :
def setdictvalto(d, value):
    for k in d:
        if isinstance(d[k], dict):
            setdictvalto(d[k], value)
        else:
            d[k] = value
>>> setdictvalto(c, 100)
>>> c
{1: 100, 2: {1: 100, 2: 100, 3: {1: 100, 2: {4: 100}}}}


Share : facebook icon twitter icon
Check if complex values of dict matches certain criteria

Check if complex values of dict matches certain criteria


By : Studio NEC
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Have added another answer with the extra requirements as specified in the comments of the previous posted answer:
code :
def printList(l, dict1):
    for l1 in l:
        if dict1.has_key(l1):
            print "withinrange"
        else:
            print "outsiderange"

file = open("test1.txt")
textfile = file.readlines()
dict={'sca4': [['BM1', 17], ['BM2', 33]], 'sca6': [['GM2', 46], ['GM2', 67], ['BM',17]]}
dict1 = {}
l =[]
key = ''
for line in textfile:
    if not line.strip():
        continue
    col1, col2, col3 = line.strip().split(" ")
    if not (key == col1):
        printList(l, dict1)
        l =[]
        key = col1
        dict1 = {}
    for value_list in dict.get(col1, []):
        #print value_list[1]
        if not (value_list[1] in l):
            l.append(value_list[1])
        if ((int(col2) <= value_list[1]) and (value_list[1] <= int(col3))):
            dict1[value_list[1]] = 'correct'
printList(l, dict1)
Using jinja to return a list of values from complex dict structure

Using jinja to return a list of values from complex dict structure


By : Tom Redfern
Date : March 29 2020, 07:55 AM
Any of those help What I would like to do is to get a list of urls i.e. [url1, url2, url3, url4, url5, url6, url7] from the following dict, so that I can assign this to a variable in my Ansible playbook: , json_query may help:
code :
- hosts: localhost
  gather_facts: no
  vars:
    dict:
      site1:
        domains:
          - canonical: url1
            redirects:
              - url2
              - url3
      site2:
        domains:
          - canonical: url4
            redirects:
              - url5
              - url6
              - url7
  tasks:
    # get redirects
    - debug: msg="{{ dict | json_query('*.domains[].redirects[]') }}"
    # get all urls
    - debug: msg="{{ dict | json_query('*.domains[].{c:to_array(canonical),r:redirects} | [].*[][]') }}"
Pandas: Convert dataframe columns into dict with col title as dict key and col values as dict values

Pandas: Convert dataframe columns into dict with col title as dict key and col values as dict values


By : Toby Howard
Date : March 29 2020, 07:55 AM
Hope that helps As indicated in comments, pandas.DataFrame.to_dict() can be used. And in your case you need to orient as record:
Code:
code :
df.to_dict('record')
df = pd.read_fwf(StringIO(u"""
          NAME              ID
    155  ARBITRARY_A    697381
    208  ARBITRARY_B    691820
    265  ARBITRARY_C    691782
    272  ARBITRARY_D    695593"""),
                 header=1, index_col=0)

print(df)
print(df.to_dict('record'))
            NAME      ID
155  ARBITRARY_A  697381
208  ARBITRARY_B  691820
265  ARBITRARY_C  691782
272  ARBITRARY_D  695593

[{u'NAME': u'ARBITRARY_A', u'ID': 697381L}, {u'NAME': u'ARBITRARY_B', u'ID': 691820L}, {u'NAME': u'ARBITRARY_C', u'ID': 691782L}, {u'NAME': u'ARBITRARY_D', u'ID': 695593L}]
Check the values in complex dict of dicts with another dict of dicts and save it a third dictionary

Check the values in complex dict of dicts with another dict of dicts and save it a third dictionary


By : Sergey Kohno
Date : March 29 2020, 07:55 AM
This might help you This solution might be better done using some other method more succinctly. However, it accomplishes the desired result.
code :
from pprint import pprint

dict3 = dict()

dict1 = {'company1':[{'age':27,'weight':200,'name':'john'},{'age':23,'weight':180,'name':'peter'}],
         'company2':[{'age':30,'weight':190,'name':'sam'},{'age':32,'weight':210,'name':'clove'},{'age':21,'weight':170,'name':'steve'}],
         'company3':[{'age':36,'weight':175,'name':'shaun'},{'age':40,'weight':205,'name':'dany'},{'age':25,'weight':160,'name':'mark'}],
         'company4':[{'age':36,'weight':155,'name':'lina'},{'age':40,'weight':215,'name':'sammy'},{'age':25,'weight':190,'name':'matt'}]
        }

dict2 = {'company2':[{'age':30},{'age':45},{'age':52}],
         'company4':[{'age':43},{'age':67},{'age':22},{'age':34},{'age':42}]
        }

for company, array in dict1.items():
    if company not in dict2:
        dict3[company] = array
    else:
        # all the ages for this company in dict1
        ages = set(map(lambda x: x['age'], array))

        for dictref in dict2[company]:
            if dictref['age'] in ages:
                dict3[company] = array
                break
pprint(dict3)
{'company1': [{'age': 27, 'name': 'john', 'weight': 200},
              {'age': 23, 'name': 'peter', 'weight': 180}],
 'company2': [{'age': 30, 'name': 'sam', 'weight': 190},
              {'age': 32, 'name': 'clove', 'weight': 210},
              {'age': 21, 'name': 'steve', 'weight': 170}],
 'company3': [{'age': 36, 'name': 'shaun', 'weight': 175},
              {'age': 40, 'name': 'dany', 'weight': 205},
              {'age': 25, 'name': 'mark', 'weight': 160}]}
How to search for key value pairs in a complex tree-like nested dict based on string values which contains a Jinja-like

How to search for key value pairs in a complex tree-like nested dict based on string values which contains a Jinja-like


By : miles.wang
Date : March 29 2020, 07:55 AM
I wish this help you You can use a generator for that purpose which traverses the nested structure and yields key-value pairs for which the criterion is met:
code :
def find_key_value_pairs(obj):
    if isinstance(obj, list):
        for item in obj:
            yield from find_key_value_pairs(item)
    elif isinstance(obj, dict):
        for key, value in obj.items():
            if isinstance(value, str) and value.startswith('##') and value.endswith('##'):
                yield key, value.strip('#')
            elif isinstance(value, (dict, list)):
                yield from find_key_value_pairs(value)
result = dict(find_key_value_pairs(test))
Related Posts Related Posts :
  • python imblearn make_pipeline TypeError: Last step of Pipeline should implement fit
  • Write to csv: columns are shifted when item in row is empty (Python)
  • DuckDuckGo search returns 'List Index out of range'
  • Python function which can transverse a nested list and print out each element
  • Python installing xlwt module error
  • Python mayavi: Adding points to a 3d scatter plot
  • Making a basic web scraper in Python with only built in libraries - Python
  • How to calculate the angle of the sun above the horizon using pyEphem
  • Fix newlines when writing UTF-8 to Text file in python
  • How to convert backward slash command in python to run on Linux
  • PyCharm Code Inspection doesn't include PEP 8
  • How can I use Python namedtuples to insert rows into mySQL database
  • Increase / Decrease Mac Address in Python from String
  • Scrollable QLabel image in PyQt5
  • (Python 2.7) Access variable from class with accessor/mutator
  • Why does "from [Module] import [Something]" takes more time than "import [Module"
  • jira python oauth: how to get the parameters for authentication?
  • Python - How to specify a relative path by jumping a subdirectory?
  • Extract scientific number from string
  • Scrapy: Python cannot find the spider
  • get the values in a given radius from numpy array
  • Is it possible to duplicate a pipe in Python, so that it has one write end but two read ends?
  • Why does wget use Firefox cookies to login on an authenticated webpage?
  • python import behaviour: different objects from same file?
  • Create YoY Graph with Matplotlib
  • Safe use of eval() or alternatives - python
  • Unix change desktop background seamlessly
  • Profiling Python code that uses multiprocessing?
  • How to query a database after render_template
  • shifting right in for loop over indices in python
  • Is there a way to switch code indentation from tabs to spaces across the project, and to keep 'hg annotate' functionalit
  • Disable/Close/Quit/Exit Terminal screen from python on Geany (Ubuntu)
  • for i in xrange() not running the complete script
  • ImportError ropevim using ropevim plugin in vim
  • How to read each line from a file into list word by word in Python
  • Creating Unique Names
  • python split a string when a keyword comes after a pattern
  • Same Python code returns different results for same input string
  • Call a Flask function every few minutes
  • Python: Using Ghost for dynamic webscraping
  • How to make while iteration faster?
  • Struggling to resolve "a float is required error" in python
  • 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?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org